For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Idea: Recursion.
Time: O(n) Space: O(n)
Code:
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
visit(root,result);
return result;
}
public void visit(TreeNode root,List<Integer> result)
{
if(root==null)
return;
visit(root.left,result);
visit(root.right,result);
result.add(root.val);
}
}
No comments:
Post a Comment