首页 > 其他 > 详细

Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-02-12 12:16:51      阅读:346      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 1 public class Solution {
 2     public TreeNode buildTree(int[] inorder, int[] postorder) {
 3         int inEnd = inorder.length-1;
 4         int postEnd = postorder.length-1;
 5         if(inEnd<0 || postEnd<0) return null;
 6         return build(inorder,0,inEnd,postorder,0,postEnd);
 7     }
 8     public TreeNode build(int []in,int inStart,int inEnd,int[]post,int postStart,int postEnd){
 9         TreeNode root = new TreeNode(post[postEnd]);
10         root.left = null;
11         root.right = null;
12         if(postStart == postEnd && post[postStart] == in[inStart]) return root;
13         int piv = inStart;
14         for(;piv<=inEnd;piv++){
15             if(in[piv]==post[postEnd]) break;
16         }
17         int leftLen = piv-inStart;
18         if(leftLen>0)
19             root.left = build(in,inStart,piv-1,post,postStart,postStart+leftLen-1);
20         if(piv<inEnd)
21             root.right = build(in,piv+1,inEnd,post,postStart+leftLen,postEnd-1);
22         return root;
23     }
24 }
View Code

Construct Binary Tree from Inorder and Postorder Traversal

原文:http://www.cnblogs.com/krunning/p/3545279.html

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