二叉树的后序遍历是对二叉树的一个基本操作。
二叉树后序遍历如下图所示:
后序遍历的结果为:DEBFCA
在后序遍历中,根节点在一棵二叉树中总是最后才会输出。这个特性启发我们可以使用“栈”这一数据结构来解决二叉树的后序遍历问题。
首先我们尝试只采用一个栈来解决这一问题:
1.先把A压入栈中
2.向根的右节点搜索,把C压入栈中
3.C没有右节点,尝试搜索C的左节点,将F压入栈中
现在问题来了,F没有子节点,我们要返回到根节点,然后从左子树继续搜索。但此时只用一个栈无法解决数据的保存和树的向上回溯。所以我们选择采用2个栈来解决之一问题。
1.从根节点开始,不断搜索右子节点,把节点压入栈1和栈2,直到右子节点为空。
2.弹出栈1的顶端的节点。
3.将节点指向弹出结点的左子树。然后再从1开始,直到栈1为空并且当前节点为空。
函数如下:
private static LinkedList VerifySquenceOfBST(TreeNode root)
{
Stack <TreeNode> stack1 = new Stack<TreeNode>();
Stack <TreeNode> stack2 = new Stack<TreeNode>();
LinkedList <Integer> out = new LinkedList<Integer>();
if(root == null)
{
return null;
}
TreeNode cur = root;
while(cur!=null || !stack1.isEmpty())
{
while(cur!=null)
{
stack1.push(cur);
stack2.push(cur);
cur =cur.right;
}
cur = stack1.pop();
cur = cur.left;
}
while(!stack2.isEmpty())
out.add(stack2.pop().val);
return out;
}
或者不采用栈的方法,也可以采用递归的方式求解。递归的方法形式很简洁,和我们自己手写找某一二叉树的后序遍历的思路基本一致。
代码如下:
private static void VerifySquenceOfBST2(TreeNode root,LinkedList <Integer> out)
{
if(root == null)
{
return ;
}
VerifySquenceOfBST2(root.left,out);
VerifySquenceOfBST2(root.right,out);
out.add(root.val);
}