zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 105 从前序与中序遍历序列构造二叉树

    105. 从前序与中序遍历序列构造二叉树

    根据一棵树的前序遍历与中序遍历构造二叉树。

    注意:
    你可以假设树中没有重复的元素。

    例如,给出

    前序遍历 preorder = [3,9,20,15,7]
    中序遍历 inorder = [9,3,15,20,7]
    返回如下的二叉树:

        3
       / 
      9  20
        /  
       15   7
    
     
    class Solution {
         private int pre=0;
        private int in=0;
        public TreeNode buildTree(int [] preorder, int [] inorder) {
            return buildTree(preorder,inorder,Integer.MAX_VALUE+1);
        }
        public TreeNode buildTree(int [] preorder,int [] inorder,long stop){
            if(pre==preorder.length){
                return null;
            }
            //走到左下第一个值可返回
            if(inorder[in]==stop){
                in++;
                return null;
            }
            //一直往左下走
            int val=preorder[pre++];
            TreeNode root=new TreeNode(val);
            
            root.left=buildTree(preorder,inorder,val);
           // 其实往右走,就是返回之前的stop
            root.right=buildTree(preorder,inorder,stop);
            return root;
        }
    }
    
  • 相关阅读:
    性能测试系列七 工具选择
    Selenium Web自动化面试题总结(下篇)
    性能测试系列六 评估压测量
    hexo 安装
    光纤收发器组网方式
    频谱仪
    交换机网管telent
    区块链共识机制
    SDH、MSTP、OTN和PTN
    ACL知识
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075550.html
Copyright © 2011-2022 走看看