https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
public List<Integer> postorderTraversal(TreeNode root)
这一题比preorder的iteration和inorder都要繁琐一些。主要是在这个过程里,中是在左右之后才进行遍历。我们需要在遍历完左右之后还要想办法回到中,这就需要一个pre节点做记录。当左边走完的时候,需要判断上一个遍历过的节点是parent节点还是右子节点。如果左边走完了之后下一个循环里前一层类递归的节点是一个parent节点,就往右走,否则如果前一个类递归的节点是右节点,就表示该节点正处于左右中的中,该输出了,接下来继续往parent节点走。根据这个算法,给出代码如下:
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> node_stack = new Stack<TreeNode>();
List<Integer> res = new LinkedList<Integer>();
TreeNode prev = null;
while(root != null || !node_stack.isEmpty()){
if(root != null){
node_stack.push(root);
root = root.left;
}else{
root = node_stack.peek();
if(root.right != null && prev != root.right){
root = root.right;
}else{
prev = root;
node_stack.pop();
res.add(root.val);
root = null;
}
}
}
return res;
}
本文详细解释了如何使用迭代方式实现二叉树的后序遍历,并提供了相应的代码实现。通过中左右的顺序遍历节点,再通过记录前一个节点来判断是否输出当前节点,从而实现后序遍历。
316

被折叠的 条评论
为什么被折叠?



