zoukankan      html  css  js  c++  java
  • 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.

    和pre & in 是一样的。

     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         // IMPORTANT: Please reset any member data you declared, as
    13         // the same Solution instance will be reused for each test case.
    14         return inorder_postorder(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    15     }
    16     public TreeNode inorder_postorder(int[] in, int is, int ie, int[] po, int ps, int pe){
    17         if(ps > pe || is > ie) return null;
    18         TreeNode root = new TreeNode(po[pe]);
    19         int ind = 0;
    20         for(int i = is; i <= ie; i++)
    21             if(in[i] == root.val){
    22                 ind = i;
    23                 break;
    24         }
    25         int len = ind - is;
    26         root.left = inorder_postorder(in, is, ind - 1,po, ps, ps + len - 1);
    27         root.right = inorder_postorder(in, ind + 1, ie, po, ps + len, pe - 1);
    28         return root;
    29     }
    30 }
  • 相关阅读:
    ansible-playbook基础
    ansible-playbook批量安装tomcat8版本
    linux
    PostgreSQL View(视图)
    PostgreSQL TRUNCATE TABLE
    PostgreSQL ALTER TABLE 命令
    redis主从环境搭建
    PostgreSQL 约束
    解决Chrome中Software Reporter Tool占CPU用过高
    C++标准模板库(STL)简介及应用
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3426343.html
Copyright © 2011-2022 走看看