首页 > 其他 > 详细

Binary Tree Inorder Traversal

时间:2015-03-04 16:44:03      阅读:195      评论:0      收藏:0      [点我收藏+]

Binary Tree Inorder Traversal

问题:

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

Recursive solution is trivial, could you do it iteratively?

思路:

  栈的方法 一直加入左节点,直到无法加入的话,弹出,弹出时观测有节点

我的代码:

技术分享
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        if(root == null)    return list;
        Stack<TreeNode> stack = new Stack<TreeNode>();  
        stack.push(root);
        do
        {
            TreeNode node = stack.peek();
            if(node.left == null)
            {
                list.add(node.val);
                stack.pop();
                if(node.right != null)
                {
                    stack.push(node.right);
                }
            }
            else
            {
                stack.push(node.left);
                node.left = null;
            }
        }while(!stack.isEmpty());
        return list;
    }
}
View Code

他人代码:

技术分享
public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<Integer>();

    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode cur = root;

    while(cur!=null || !stack.empty()){
        while(cur!=null){
            stack.add(cur);
            cur = cur.left;
        }
        cur = stack.pop();
        list.add(cur.val);
        cur = cur.right;
    }

    return list;
}
View Code

学习之处:

  • 自己的方法虽然可行,但是破坏了原来树的结构
  • 别人的代码用了一个特别妙的方法,加入了另外一个变量名cur,通过对cur继续一直左子树的遍历,同时cur=cur.right 防止进行死循环

 

Binary Tree Inorder Traversal

原文:http://www.cnblogs.com/sunshisonghit/p/4313411.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!