标签:
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?
需要记住上一下访问的元素pre,如果pre是当前的父节点,则将当前节点放入stack,向下遍历,否则的话就是向上返回,如果pre是当前的左孩子的话,则把右孩子放入stack,向下遍历,否则的话,则当前元素应被访问,然后向上返回。
还有种用两个stack的做法,具体参考leetcode官方答案。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
stack.push(root);
TreeNode pre = null;
while (!stack.isEmpty()) {
TreeNode node = stack.peek();
// Traversing down
if (pre == null || pre.left == node || pre.right == node) {
if (node.left != null) {
stack.push(node.left);
} else if (node.right != null) {
stack.push(node.right);
}
} else if ( node.left == pre) {
if (node.right != null) {
stack.push(node.right);
}
} else {
list.add(node.val);
stack.pop();
}
pre = node;
}
return list;
}
}
145. Binary Tree Postorder Traversal
标签:
原文地址:http://www.cnblogs.com/shini/p/4436558.html