您的位置:首页 > 其它

后序遍历二叉树

2015-08-16 23:22 337 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/kakabest123/article/details/47709251

递归方法和之前的几乎一致,不再赘述。

考虑非递归方法:
后序遍历顺序是:左,右,根
即左孩子和右孩子都遍历输出了之后,才遍历子树的根节点。

public ArrayList<Integer> postorderTraversal(TreeNode root) {

ArrayList<Integer> lst = new ArrayList<Integer>();

if(root == null)
return lst;

Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);

TreeNode prev = null;
while(!stack.empty()){
TreeNode curr = stack.peek();

// go down the tree.
//check if current node is leaf, if so, process it and pop stack,
//otherwise, keep going down
if(prev == null || prev.left == curr || prev.right == curr){
//prev == null is the situation for the root node
if(curr.left != null){
stack.push(curr.left);
}else if(curr.right != null){
stack.push(curr.right);
}else{
stack.pop();
lst.add(curr.val);
}

//go up the tree from left node
//need to check if there is a right child
//if yes, push it to stack
//otherwise, process parent and pop stack
}else if(curr.left == prev){
if(curr.right != null){
stack.push(curr.right);
}else{
stack.pop();
lst.add(curr.val);
}

//go up the tree from right node
//after coming back from right node, process parent node and pop stack.
}else if(curr.right == prev){
stack.pop();
lst.add(curr.val);
}

prev = curr;
}

return lst;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: