zoukankan      html  css  js  c++  java
  • Construct Binary Tree From Preorder and Inorder Traversal

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

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

     1 /**
     2  * Definition for a binary tree node.
     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         if (preorder == null) return null;
    13         
    14         int preLeft = 0, preRight = preorder.length - 1, inLeft = 0, inRight = inorder.length -1;
    15         return buildTree(preorder, inorder, preLeft, preRight, inLeft, inRight);
    16     }
    17     
    18     private TreeNode buildTree(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight) {
    19         if (preLeft > preRight) return null;
    20         
    21         TreeNode temp = new TreeNode(preorder[preLeft]);
    22         if (preLeft == preRight)
    23             return temp;
    24         
    25         int index = inLeft;
    26         while (index < inRight && inorder[index] != preorder[preLeft])
    27             index++;
    28             
    29         temp.left = buildTree(preorder, inorder, preLeft + 1, preLeft + index - inLeft, inLeft, index - 1);
    30         temp.right = buildTree(preorder, inorder, preLeft + index - inLeft + 1, preRight, index + 1, inRight);
    31         return temp;
    32     }
    33 }
  • 相关阅读:
    【转载】分布式环境Raft一致性共识算法解读
    从码农到工程师:只要做到这6点
    产品思维的修炼–技术的必修课
    工具篇
    安全测试
    测试体会
    测试题目
    软件测试工具
    常见的性能测试方法
    性能测试在软件测试的周期位置
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6688582.html
Copyright © 2011-2022 走看看