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

[leetcode]Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-07-31 23:26:00      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   strong   io   for   

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.

算法:很基础。跟[leetcode]Construct Binary Tree from Preorder and Inorder Traversal类似,根据中序序列和后序序列构建二叉树。

 1 public class Solution {
 2     public TreeNode buildTree(int[] inorder, int[] postorder) {
 3          if(inorder == null || postorder == null || inorder.length != postorder.length || inorder.length == 0) return null;
 4          int length = inorder.length ;
 5          int val = postorder[length - 1];
 6          int mid = 0;
 7          for(int i = 0; i < length; i++){
 8              if(val == inorder[i]){
 9                  mid = i;
10                  break;
11              }
12          }
13          int[] leftInorder = Arrays.copyOfRange(inorder, 0, mid);
14          int[] leftPost = Arrays.copyOfRange(postorder, 0, mid);
15          int[] rightInorder = Arrays.copyOfRange(inorder, mid + 1, length);
16          int[] rightPost = Arrays.copyOfRange(postorder, mid, length - 1);
17          TreeNode root = new TreeNode(val);
18          root.left = buildTree(leftInorder,leftPost);
19          root.right = buildTree(rightInorder, rightPost);
20          return root;
21      
22     }
23 }

 

[leetcode]Construct Binary Tree from Inorder and Postorder Traversal,布布扣,bubuko.com

[leetcode]Construct Binary Tree from Inorder and Postorder Traversal

标签:style   blog   http   color   os   strong   io   for   

原文地址:http://www.cnblogs.com/huntfor/p/3883524.html

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