zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Ubuntu16.04 + OpenCV源码 + Qt5.10 安装、配置
    DML和DQL
    初识MySql
    表单校验
    使用jQuery操作DOM
    jQuery中的事件与动画
    jQuery选择器
    初识jQuery
    JavaScript对象及初识OOP
    JavaScript操作DOM对象
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3536017.html
Copyright © 2011-2022 走看看