新博文地址:
[leetcode]Binary Tree Postorder Traversal
Binary Tree Postorder Traversal
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].
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
后序遍历,题中提示说不让用递归,让用迭代。明天再搞吧。
先给出一个递归版本:
ArrayList<Integer> result = new ArrayList<Integer>();
public ArrayList<Integer> postorderTraversal(TreeNode root) {
if(root == null){
return result;
}
postOrder(root);
return result;
}
private void postOrder(TreeNode root){
if(root.left != null){
postorderTraversal(root.left);
}
if(root.right != null){
postorderTraversal(root.right);
}
result.add(root.val);
}