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].
一刷
二刷
方法同144, 不过采用每次insert到数组头部,那么就变成了root, right, left的顺序
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
while(root!=null || !stack.isEmpty()){
if(root == null){
root = stack.pop().left;
}
else{
res.add(0, root.val);
stack.push(root);
root = root.right;
}
}
return res;
}
}