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

LeetCode-Binary Tree Postorder Traversal

时间:2015-03-16 12:28:00      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

 1 Given a binary tree, return the postorder traversal of its nodes values.
 2 
 3 For example:
 4 Given binary tree {1,#,2,3},
 5    1
 6      7      2
 8     /
 9    3
10 return [3,2,1].
11 
12 Note: Recursive solution is trivial, could you do it iteratively?

Recursive:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public List<Integer> postorderTraversal(TreeNode root) {
 
        List<Integer> list = new ArrayList<Integer>();
        if(root == null){
            return list;
        }
        list.addAll(postorderTraversal(root.left));
        list.addAll(postorderTraversal(root.right));
        list.add(root.val);
        
        return list;
        
    }
}

 

 

Iterative:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
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>();
         ArrayList<TreeNode> visited = new ArrayList<TreeNode>();
         
         stack.push(root);
         while(root != null || !stack.isEmpty()){
             if(root.left != null && !visited.contains(root.left)){
                 stack.push(root.left);
                 root=root.left;
             }
             
             else if(root.right != null && !visited.contains(root.right)){
                 stack.push(root.right);
                 root = root.right;
             }
             
             else{
                 visited.add(root);
                 list.add(stack.pop().val);
                 if(!stack.isEmpty()){
                    root = stack.peek();
                 }
                 else {
                     root=null;
                 }
                 
             }
             
         }
         return list;
    }

}

 

LeetCode-Binary Tree Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/4341256.html

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