zoukankan      html  css  js  c++  java
  • Binary Tree Inorder Traversal

    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 防止进行死循环

    if(null == head) return new ArrayList<Integer>();
    List<Integer> inOrder = new ArrayList<Integer>();
    Stack<TreeNode> nodeStack = new Stack<TreeNode>();
    nodeStack.push(head);

    while(!nodeStack.isEmpty()){
    TreeNode curTopNode = nodeStack.peek();
    if(curTopNode.left == null){
    inOrder.add(curTopNode.val);
    nodeStack.pop();
    if(null != curTopNode.right){
    nodeStack.add(curTopNode.right);
    }
    }else{
    nodeStack.add(curTopNode.left);
    }
    }

    return inOrder;

  • 相关阅读:
    Win7+IIS伪静态 UrlRewriter配置
    让VS2010打包工具找回丢失的.net 2.0 .
    高效注册DLL控件 让你的IE浏览器复活
    查询及删除重复记录的方法
    .NET代码模板生成工具CodeSmith 5.0.1 专业版完美版下载
    如何使用CslaGen生成CSLA DAL层代码
    用C# + WebBrowser控件抓取AJAX页面的内容[转]
    了解IIS6应用程序池假死问题解决办法
    美化界面2
    C# WebBrowser高级应用
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4313411.html
Copyright © 2011-2022 走看看