二叉树的非递归遍历

有些程序,不动手写,就不知道自己不会。

前序和中序这里实现的有些问题,还是看北大的算法教程靠谱。不过,这里的后序还是不错的

前序遍历

static void PreOrderTraverse(BinaryTreeNode root)
{
    BinaryTreeNode temp = root.left;
    Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
    Console.WriteLine(root.data);
    stack.Push(root);
    while (stack.Count > 0 || temp != null)
    {
        while (temp != null)
        {
            Console.WriteLine(temp.data);
            stack.Push(temp);//要把当前的节点放入栈中,以备回溯到这个节点时,取其右孩子
            temp = temp.left;
        }
        temp = stack.Pop();
        temp = temp.right;
    }
}


中序遍历

static void InOrderTraverse2(BinaryTreeNode root)
{
    BinaryTreeNode temp = root.left;
    Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
    stack.Push(root);
    while (stack.Count > 0 || temp != null)
    {
        while (temp != null)
        {
            stack.Push(temp);
            temp = temp.left;
        }
        temp = stack.Pop();
        Console.WriteLine(temp.data);
        temp = temp.right;
    }
}


后序遍历比较麻烦,当前节点的左孩子还是右孩子的处理方法不一样。先处理左子树,再处理右子树,最后处理当前节点,但是当处理当前节点的时候如何判断是从左子树返回的还是从右子树返回的呢?这就需要当前节点curr的前一个节点pre。

static void PostOrderTraversa2(BinaryTreeNode root)
{
    Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
    stack.Push(root);
    BinaryTreeNode prev = null;
    BinaryTreeNode curr = null;
    while (stack.Count > 0)
    {
        curr = stack.Peek();
        if (prev == null || prev.left == curr || prev.right == curr)//节点在漫游
        {
            if (curr.left != null)
                stack.Push(curr.left);
            else if (curr.right != null)
                stack.Push(curr.right);
        }
        else if (curr.left == prev)//下面的都是节点开始回溯
        {
            if (curr.right != null)
                stack.Push(curr.right);
        }
        else//当是叶子节点(prev == curr)或者prev节点是curr的右子树的时候(curr.right == prev)
        {
            Console.WriteLine(curr.data);
            stack.Pop();
        }
        prev = curr;
    }
}

http://www.cnblogs.com/MichaelYin/archive/2010/12/23/1915316.html



你可能感兴趣的:(null,2010)