• 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         return buildTreeHelp(inorder, postorder, 0, length - 1, 0, length - 1);
    14     }
    15     public TreeNode buildTreeHelp(int[] inorder, int[] postorder, int startI, int endI, int startP, int endP){
    16         TreeNode root = null;
    17         if(startI <= endI){
    18             root = new TreeNode(postorder[endP]);
    19             int rootPosition = startI;
    20             int newendP = startP;
    21             for(int i = startI; i <= endI; ++i){
    22                 if(inorder[i] == postorder[endP]){
    23                     rootPosition = i;
    24                     break;
    25                 }
    26                 else
    27                     ++newendP;
    28             }
    29             root.left = buildTreeHelp(inorder, postorder, startI, rootPosition - 1, startP, newendP - 1);
    30             root.right = buildTreeHelp(inorder, postorder, rootPosition + 1, endI, newendP, endP - 1);
    31         }
    32         return root;
    33     }
    34 }
  • 相关阅读:
    谷歌浏览器禁止缩放和全面屏显示
    常用正则表达式
    封装时间函数
    年月日,时分秒,星期
    昨天,明天,月初,月末,最近七天,最近一个月,今天零时js
    React框架
    javaweb基础备忘
    一些java基础知识的备忘
    查看deepin版本
    java中堆栈的一些理解备忘
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3536017.html
Copyright © 2020-2023  润新知