Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
思路一:后序遍历:左,右,根。所以对于每个节点,用三种颜色-1,0,1表示左节点未访问,左节点已访问但右节点未访问,左右节点均已访问。对于均已访问的节点,则保存结果。
思路二:以根、右、左的方式先序遍历,然后将结果逆序,就变成了左、右、根的顺序。更简洁。
思路代码1:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
if(root == null ) return ans;
Stack<TreeNode> stackNode = new Stack<TreeNode>();
Stack<Integer> stackFlag = new Stack<Integer>();
stackNode.push(root);
stackFlag.push(-1);
while(!stackNode.isEmpty()){
TreeNode top = stackNode.peek();
Integer flag = stackFlag.peek();
if(top == null){
stackNode.pop();
stackFlag.pop();
continue;
}
if(flag == -1){
stackFlag.pop();
stackFlag.push(0);
if(stackNode.peek().left != null){
stackNode.push(stackNode.peek().left);
stackFlag.push(-1);
}
}else if(flag == 0){
stackFlag.pop();
stackFlag.push(1);
stackNode.push(stackNode.peek().right);
stackFlag.push(-1);
}else{
ans.add(stackNode.pop().val);
stackFlag.pop();
}
}
return ans;
}
}
思路2代码:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
while (root != null || !stack.isEmpty()) {
if (root != null) {
stack.push(root);
res.add(0, root.val);
root = root.right;
} else {
root = stack.pop();
root = root.left;
}
}
return res;
}
}