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

  • 相关阅读:
    NET中的类型和装箱/拆箱原理
    转 C# 装箱和拆箱[整理]
    理解线程同步
    IsBackground的理解
    赛马会面试题
    FTP上传类
    FTPS加密上传
    转载WPF SDK研究 之 AppModel
    SQL Server查看错误日志存档编号及其详情
    Hive基础编程入门(一)
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4129712.html
Copyright © 2011-2022 走看看