• 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 }
  • 相关阅读:
    委托和异步方法
    线程池_ThreadPool
    委托_deleget
    一步一步实现视频播放器client(二)
    mysql忘记password
    POJ 2456 Aggressive cows (二分 基础)
    Fragment小结
    Cocos2d-x粒子系统
    淘宝数据库OceanBase SQL编译器部分 源代码阅读--解析SQL语法树
    C与C++在形參的一点小差别
  • 原文地址:https://www.cnblogs.com/birdhack/p/4088508.html
Copyright © 2020-2023  润新知