码迷,mamicode.com
首页 > 其他好文 > 详细

5. Binary Tree Postorder Traversal

时间:2014-12-30 20:33:56      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

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;
  }
}

5. Binary Tree Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/hechengzhu/p/4194328.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!