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;
        }
    }
    
  • 相关阅读:
    ACM中java的使用
    hdu 1273最大流
    1066N !最右边非零数
    关于为什么要建退边的原因
    浅析指向指针的指针其作用
    poj 1860 bellman 求正环
    poj 3461
    poj 2031
    poj 1068
    strncpy的用法
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075550.html
Copyright © 2011-2022 走看看