5. 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},
?
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;
}
}
轉(zhuǎn)載于:https://www.cnblogs.com/hechengzhu/p/4194328.html
總結(jié)
以上是生活随笔為你收集整理的5. Binary Tree Postorder Traversal的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么在pe格式c盘 PE格式的C盘怎么创
- 下一篇: 摆脱科技僵尸,回归生龙活虎