首页 > 其他 > 详细

leetcode---Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-01-29 14:34:55      阅读:332      评论:0      收藏:0      [点我收藏+]

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

 

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

leetcode---Construct Binary Tree from Inorder and Postorder Traversal

原文:http://www.cnblogs.com/averillzheng/p/3536017.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!