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 }
  • 相关阅读:
    Nginx配置文件nginx.conf中文详解
    tomcat nginx默许的post大小限制
    Unrecognized Windows Sockets error: 0: JVM_Bind 异常解决办法
    服务器被上传非法文件,查找命令
    jQuery Event.which 属性详解
    jQuery中$.fn的用法示例介绍
    Spring4 学习教程
    注意Hibernate4在开发当中的一些改变
    ubuntu PATH 出错修复
    SpringMVC与SiteMesh
  • 原文地址:https://www.cnblogs.com/birdhack/p/4088508.html
Copyright © 2011-2022 走看看