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;
        }
    }
    
  • 相关阅读:
    ###STL学习--标准模板库
    打包C#程序
    ###学习《Effective C++》
    [ZJOI2007]棋盘制作
    [NOI2012]美食节
    [SCOI2012]奇怪的游戏
    5120: [2017国家集训队测试]无限之环
    序列取数
    1028: [JSOI2007]麻将
    1011: [HNOI2008]遥远的行星
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13076196.html
Copyright © 2011-2022 走看看