• 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 }
  • 相关阅读:
    GDOI 2019 退役记
    SHOI2019 游记
    【WC2014】紫荆花之恋
    PKUWC 2019 & NOIWC2019 比赛总结 Formal Version
    WC 2019 颓废记
    VDUVyRLYJC
    Git学习
    DOM学习笔记
    python基础---->AJAX的学习
    python基础---->进程、线程及相关等
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3426343.html
Copyright © 2020-2023  润新知