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

    本题和之前的105题比较类似,解法可以用相同的想法来解决,代码如下:

     1 /**
     2  * Definition for a binary tree node.
     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         return helper(postorder.length-1,0,inorder.length-1,inorder,postorder);
    13     }
    14     public TreeNode helper(int endPost,int startIn,int endIn,int[] inorder,int[] postorder){
    15         if(endPost<0||startIn>endIn) return null;
    16         TreeNode root = new TreeNode(postorder[endPost]);
    17         int indexIn = 0;
    18         for(int i=startIn;i<=endIn;i++){
    19             if(inorder[i]==root.val){
    20                 indexIn = i;
    21             }
    22         }
    23         root.left  =helper(endPost-1-(endIn-indexIn),startIn,indexIn-1,inorder,postorder);
    24         root.right = helper(endPost-1,indexIn+1,endIn,inorder,postorder);
    25         return root;
    26     }
    27 }
  • 相关阅读:
    读取数据变JSON传值!
    YII2.0多条件查询升级版
    JS跳转页面方法
    yii的简单片段缓存
    我读过的最好的epoll讲解--转自”知乎“
    I/O多路复用详解
    ”open-close"prinple (OCP)
    获取本机的IPv4或者v6地址
    .Net 下未捕获异常的处理
    TCP断开连接的过程
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6477188.html
Copyright © 2011-2022 走看看