• leetcode--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 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         int length = inorder.length;
    13         return buildTreeHelp(preorder,inorder,0,length - 1, 0, length - 1);
    14     }
    15     
    16     public TreeNode buildTreeHelp(int[] preorder, int[] inorder, int pstart, int pend, int istart,int iend){
    17         TreeNode root = null;
    18         if(istart <= iend){
    19             root = new TreeNode(preorder[pstart]);
    20             int rootPosition = istart;
    21             int newpend = pstart;
    22             for(int i = istart; i <= iend; ++i){
    23                 if(inorder[i] == preorder[pstart]){
    24                     rootPosition = i;
    25                     break;
    26                 }
    27                 else
    28                     ++newpend;                
    29             }
    30             root.left = buildTreeHelp(preorder, inorder, pstart + 1, newpend, istart, rootPosition - 1);
    31             root.right = buildTreeHelp(preorder, inorder, newpend + 1, pend, rootPosition + 1, iend);
    32         }
    33         return root;
    34     }
    35 }
  • 相关阅读:
    html 父容器和子容器通信
    5.7.13mysql 无法登陆
    c# foreach枚举器
    WPF bitmap转bitmapimage 使用 CreateBitmapSourceFromHBitmap内存泄漏
    c# 另存为excel
    CRC循环校验码
    一般处理程序
    DSS->数仓->数据集市->数据湖->数据中台->商业智能
    常见的消息中间件对比
    Dockerfile详解
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3536018.html
Copyright © 2020-2023  润新知