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]
.
Note: Recursive solution is trivial, could you do it iteratively?
解法一:Python版本:
class Solution:
# @param root, a tree node
# @return a list of integers
def postorderTraversal(self, root):
temp = root
result = []
if temp == None:
return result
stack = []
stack.insert(0, temp)
while stack:
temp = stack[0]
stack.remove(temp)
if temp.left != None:
stack.insert(0, temp.left)
if temp.right != None:
stack.insert(0, temp.right)
result.append(temp.val)
result.reverse()
return result
解法二:Java版本:
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null)
{
return list;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode temp = root;
stack.push(temp);
while(!stack.isEmpty())
{
TreeNode t = stack.pop();
if(t.left!=null)
{
stack.push(t.left);
}
if(t.right!=null)
{
stack.push(t.right);
}
list.add(t.val);
}
Collections.reverse(list);
return list;
}
}