码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 94 Binary Tree Inorder Traversal ----- java

时间:2016-10-20 19:23:49      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

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

For example:
Given binary tree [1,null,2,3],

   1
         2
    /
   3

 

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

 

求二叉树的中序遍历,要求不是用递归。

 

先用递归做一下,很简单。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List result = new ArrayList<Integer>();
    public List<Integer> inorderTraversal(TreeNode root) {
        if( root == null)
            return result;
        getResult(root);
        return result;        
    }

    public void getResult(TreeNode root){
        if( root.left != null)
            getResult(root.left);
        result.add(root.val);
        if( root.right != null)
            getResult(root.right);
    }
    
}

 不用递归,用栈实现也是很简单的。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    List result = new ArrayList<Integer>();
    public List<Integer> inorderTraversal(TreeNode root) {
        if( root == null)
            return result;
        Stack stack = new Stack<TreeNode>();
        TreeNode node = root;
        while( true ){
            if( node.left == null){
                result.add(node.val);
                if( node.right == null ){
                    if( stack.isEmpty() )
                        break;
                    else
                        node = (TreeNode) stack.pop();
                }else{
                    node = node.right;
                }
                
            }else{
                TreeNode flag = node;
                node = node.left;
                flag.left = null;
                stack.push(flag);
                
            }
        }


        return result;        
    }
    
}

 

leetcode 94 Binary Tree Inorder Traversal ----- java

标签:

原文地址:http://www.cnblogs.com/xiaoba1203/p/5981983.html

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