前-中-后 序遍历

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TraversBTree : MonoBehaviour
{
    
    
    //前序遍历
    public void TraversalByPreorder(BTree tree)
    {
    
    
        Stack<BTreeNode> stack = new Stack<BTreeNode>();
        BTreeNode t = tree.Root;

        while (t != null || stack.Count > 0)
        {
    
    
            while (t != null)
            {
    
    
                Debug.LogError(t.Value);
                stack.Push(t);
                t = t.leftChild;
            }
            if (stack.Count > 0)
            {
    
    
                t = stack.Pop();
                t = t.rightChild;
            }
        }
    }
    //中序遍历
    public void TraversalByInorder(BTree tree)
    {
    
    
        Stack<BTreeNode> stack = new Stack<BTreeNode>();
        BTreeNode t = tree.Root;

        while (t != null || stack.Count > 0)
        {
    
    
            while (t != null)
            {
    
    
                stack.Push(t);
                t = t.leftChild;
            }
            if (stack.Count > 0)
            {
    
    
                t = stack.Pop();
                Debug.LogError(t.Value);
                t = t.rightChild;
            }
        }
    }
    /// <summary>
    /// 后续遍历需要解释下 后序遍历应该是最后访问根 其他顺序不变 那么怎么才能保证我们最后访问到的顺序为 左子树 - 右子树木 - 根呢?
    /// 栈这个结构很符合 我们只需要将 根 - 右子树 - 左子树 按照顺序压入栈,最后出栈就可以正确得到后序遍历结果具体操作如下
    /// </summary>
    /// <param name="tree"></param>
    public void TraversalByPostorder(BTree tree)
    {
    
    
        //1号栈负责操作开始时候将根压入 然后弹出压入2号栈底 然后负责开始判断是否有 左子树 和 右子树 先左后右很重要 1号栈 先入左后入右 可以爆炸弹出时候先是右后是左
        //这样在循环最开始时候1号栈 弹出压入到2号栈的就一定是右子树 从而保证了2号栈的进栈顺序为 根 - 右子树 - 左子树 从而保证了结果 
        Stack<BTreeNode> stack1 = new Stack<BTreeNode>();
        //2号栈负责里面顺序为 根 - 右子树 - 左子树 最后出栈打印就是结果 。
        Stack<BTreeNode> stack2 = new Stack<BTreeNode>();
        BTreeNode root = tree.Root;
        stack1.Push(root);
        while (stack1.Count > 0)
        {
    
    
            BTreeNode t = stack1.Pop();
            stack2.Push(t);
            if (t.leftChild != null)
            {
    
    
                stack1.Push(t.leftChild);
            }
            if (t.rightChild != null)
            {
    
    
                stack1.Push(t.rightChild);
            }
        }
        while (stack2.Count > 0)
        {
    
    
            Debug.LogError(stack2.Pop().Value);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39691716/article/details/121465152