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

[LeetCode-JAVA] Binary Tree Inorder Traversal

时间:2015-05-21 10:33:26      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

For example:
Given binary tree {1,#,2,3},

   1
         2
    /
   3

 

return [1,3,2].

思路:题中规定用循环代替递归求解,用辅助stack来存储遍历到的节点,如果不为空则入栈,否则出栈赋值,并指向其右节点。

技术分享

 

代码:

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> req = new ArrayList<Integer>();
        
        if(root == null)
            return req;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        
        while(!stack.isEmpty() || root != null){
            if(root != null){
                stack.push(root);
                root = root.left;
            }else{
                TreeNode temp = stack.pop();
                req.add(temp.val);
                root = temp.right;       //最重要的一步
            }
            
        }
        
        return req;
    }
}

参考链接: http://www.programcreek.com/2012/12/leetcode-solution-of-binary-tree-inorder-traversal-in-java/

[LeetCode-JAVA] Binary Tree Inorder Traversal

标签:

原文地址:http://www.cnblogs.com/TinyBobo/p/4518975.html

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