zoukankan      html  css  js  c++  java
  • Leetcode-Construct Binary Tree from inorder and preorder travesal

    Given preorder and inorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    Solution:

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public TreeNode buildTree(int[] preorder, int[] inorder) {
    12         TreeNode root = buildTreeRecur(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
    13         return root;
    14     }
    15 
    16     public TreeNode buildTreeRecur(int[] preorder, int[] inorder, int preS, int preE, int inS, int inE){
    17         if (preS>preE) return null;
    18         if (preS==preE){
    19             TreeNode leaf = new TreeNode(preorder[preS]);
    20             return leaf;
    21         }
    22 
    23         int rootVal = preorder[preS];
    24         int index = inS;
    25         for (int i=inS;i<=inE;i++)
    26             if (inorder[i]==rootVal){
    27                 index = i;
    28                 break;
    29             }
    30 
    31         int leftLen = index-inS;
    32         int rightLen = inE - index;
    33    
    34         TreeNode leftChild = buildTreeRecur(preorder,inorder,preS+1,preS+leftLen,inS,index-1);
    35         TreeNode rightChild = buildTreeRecur(preorder,inorder,preE-rightLen+1,preE,index+1,inE);
    36         TreeNode root = new TreeNode(rootVal);
    37         root.left = leftChild;
    38         root.right= rightChild;
    39         return root;
    40    }
    41       
    42 }

    Construct Binary Tree from Preorder and Inorder Traversal

  • 相关阅读:
    页面实现文件的下载
    微信小程序拉起登录的操作
    css3之border-radius理解
    web前端常用网站--更新中
    小程序中遇见文件过大的话就需要分包
    JS中的“&&”与“&”和“||”“|”有什么区别?
    ts中有时莫名报错
    浏览器解析JavaScript的原理
    在vue中axios的问题
    eslint的规则
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4129712.html
Copyright © 2011-2022 走看看