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.

[解题思路]

与上题类似Construct Binary Tree from Preorder and Inorder Traversal 确定左右子树的序列,

递归建立树,唯一不同在于后序遍历,根节点在最后一个元素

 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         // Start typing your Java solution below
13         // DO NOT write main() function
14         if (postorder == null || inorder == null) {
15             return null;
16         }
17         int postLen = postorder.length;
18         int inLen = inorder.length;
19         if (postLen == 0 || inLen == 0) {
20             return null;
21         }
22 
23         return constructTree(postorder, 0, postLen - 1, inorder, 0, inLen - 1);
24     }
25     
26     public static TreeNode constructTree(int[] postorder, int postStart, int postEnd,
27             int[] inorder, int inStart, int inEnd) {
28         int rootVal = postorder[postEnd];
29         TreeNode root = new TreeNode(rootVal);
30         root.left = null;
31         root.right = null;
32         
33         if(postStart == postEnd && postorder[postStart] == inorder[inStart]){
34             return root;
35         }
36         
37         int i = inStart;
38         for(; i <= inEnd; i++){
39             if(inorder[i] == rootVal){
40                 break;
41             }
42         }
43         int leftLen = i - inStart;
44         if(leftLen > 0){
45             root.left = constructTree(postorder, postStart, postStart + leftLen - 1,
46                     inorder, inStart, i - 1);
47         }
48         if(inEnd > i){
49             root.right = constructTree(postorder, postStart + leftLen, postEnd - 1,
50                     inorder, i + 1, inEnd);
51         }
52         return root;
53     }
54 }

 

转载于:https://www.cnblogs.com/feiling/p/3277053.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值