zoukankan      html  css  js  c++  java
  • LeetCode Construct Binary Tree from Inorder and Postorder Traversal

    Given inorder and postorder 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[] inorder, int[] postorder) {
    12         int length=inorder.length;
    13         if (length==0) return null;
    14         int rootnumber=postorder[length-1];
    15         TreeNode root = new TreeNode(rootnumber);
    16 
    17         if (length==1) return root;
    18         int indexRoot = 0;
    19         for (int i = 0; i < length; i++) {
    20             if (inorder[i]==rootnumber){
    21                 indexRoot=i;
    22                 break;
    23             }
    24         }
    25         int[] left=new int[indexRoot];
    26         int[] leftPost=new int[indexRoot];
    27         int[] right=new int[length-indexRoot-1];
    28         int[] rightPost=new int[length-indexRoot-1];
    29         for (int i = 0; i < indexRoot; i++) {
    30             left[i]=inorder[i];
    31             leftPost[i]=postorder[i];
    32         }
    33         for (int i = indexRoot+1; i <length ; i++) {
    34             right[i-1-indexRoot]=inorder[i];
    35             rightPost[i-1-indexRoot]=postorder[i-1];
    36         }
    37         root.left=buildTree(left,leftPost);
    38         root.right=buildTree(right,rightPost);
    39         return root;
    40     }
    41 }
  • 相关阅读:
    费用流
    平面最近点对
    纸牌均分问题
    cdq分治模板
    费解的开关
    斐波那契和排列组合性质
    主席树
    Springboot使用EasyExcel(仅限自己收藏)
    vue项目中h5移动端中通过flex布局实现首尾固定,中间滚动(借鉴)
    vue路由参数的获取、添加和替换
  • 原文地址:https://www.cnblogs.com/birdhack/p/4088508.html
Copyright © 2011-2022 走看看