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

lintcode-easy-Binary Tree Inorder Traversal

时间:2016-02-21 11:29:05      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, return the inorder traversal of its nodes‘ values.

Example

Given binary tree {1,#,2,3},

   1
         2
    /
   3

 

return [1,3,2].

Challenge

Can you do it without recursion?

两种做法:

1. 使用递归, 思路比较直接,不多说了

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> result = new ArrayList<Integer>();
        
        if(root == null)
            return result;
            
        helper(root, result);
        
        return result;
    }
    
    public void helper(TreeNode root, ArrayList<Integer> result){
        if(root == null)
            return;
        else{
            helper(root.left, result);
            result.add(root.val);
            helper(root.right, result);
            return;
        }
    }
}

 

2. 不使用递归的方法,使用一个stack,维护一个reference p

当p非null时,将p入栈,p指向左子树

当p为null时,栈顶元素出栈,加入arraylist,p再指向右子树

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> result = new ArrayList<Integer>();
        
        if(root == null)
            return result;
        
        TreeNode p = root;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        
        while(p != null || !stack.isEmpty()){
            if(p != null){
                stack.push(p);
                p = p.left;
            }
            else{
                p = stack.pop();
                result.add(p.val);
                p = p.right;
            }
        }
        
        return result;
    }
}

 

 

lintcode-easy-Binary Tree Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5204578.html

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