码迷,mamicode.com
首页 > 其他好文 > 详细

106. Construct Binary Tree from Inorder and Postorder Traversal

时间:2018-09-20 11:28:23      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:root   ret   public   for   new   bin   tar   int   ++   

 1 class Solution {
 2     public TreeNode buildTree(int[] inorder, int[] postorder) {
 3         return helper(postorder.length-1, 0, inorder.length - 1, inorder, postorder);
 4         
 5     }
 6     
 7     public TreeNode helper(int post, int inStart, int inEnd, int[] inorder, int[] postorder) {
 8         if(inStart > inEnd || post < 0) {
 9             return null;
10         }
11         TreeNode root = new TreeNode(postorder[post]);
12         int rootIndex = 0;
13         for(int i = inStart; i <= inEnd; i++) {
14             if(inorder[i] == root.val) {
15                 rootIndex = i;
16                 break;
17             }
18         }
19         
20         root.right = helper(post-1, rootIndex+1, inEnd, inorder, postorder);
21         root.left = helper(post - (inEnd - rootIndex + 1), inStart, rootIndex - 1, inorder, postorder );
22         // inEnd - rootIndex注意是inEnd去减, 不是inorder.length
23         return root;
24     }
25 }

 

106. Construct Binary Tree from Inorder and Postorder Traversal

标签:root   ret   public   for   new   bin   tar   int   ++   

原文地址:https://www.cnblogs.com/goPanama/p/9678651.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!