Given a binary tree, return the_postorder_traversal of its nodes' values.
For example:
Given binary tree[1,null,2,3]
,
1
\
2
/
3
return[3,2,1]
.
Note:Recursive solution is trivial, could you do it iteratively?
tag: binary tree
post order is just reverse of pre order
/**
* 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<>();
if (root == null) return ans;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode cur = stack.pop();
ans.add(cur.val);
if (cur.left != null) stack.push(cur.left);
if (cur.right != null) stack.push(cur.right);
}
Collections.reverse(ans);
return ans;
}
}