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 }
  • 相关阅读:
    linux进阶1
    linux中使用mysql数据库
    计算机是如何启动的
    宿主机mount虚拟机镜像文件
    SHA1算法原理
    KVM初始化过程
    关于内存对齐
    thread_info&内核栈
    gradlew compileDebug --stacktrace -info
    Android listview子控件的的点击事件(转)
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6477188.html
Copyright © 2011-2022 走看看