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

Construct Binary Tree from Inorder and Postorder Traversal

时间:2016-07-08 01:28:44      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

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

 Notice

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

Example

Given inorder [1,2,3] and postorder [1,3,2], return a tree:

  2
 / 1   3
分析:
这是非常典型的递归问题,postorder的最后一个是root,在inorder里面找出root的位置,左边部分为左子树,右边部分为右子树,稍微麻烦的部分就是确定左子树和右子树的starting index。
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12  
13  
14 public class Solution {
15     /**
16      *@param inorder : A list of integers that inorder traversal of a tree
17      *@param postorder : A list of integers that postorder traversal of a tree
18      *@return : Root of a tree
19      */
20     public TreeNode buildTree(int[] inorder, int[] postorder) {
21         if (inorder == null || postorder == null || postorder.length == 0 || inorder.length != postorder.length) return null;
22         
23         return buildTree(inorder, 0, postorder, 0, inorder.length);
24         
25     }
26     
27     public TreeNode buildTree(int[] inorder, int inStart, int[] postorder, int postStart, int length) {
28         if (length <= 0) return null;
29         TreeNode root = new TreeNode(postorder[postStart + length - 1]);
30 
31         int index = findIndex(inorder, root.val);
32         root.left = buildTree(inorder, inStart, postorder, postStart, index - inStart);
33         root.right = buildTree(inorder, index + 1, postorder, postStart + (index - inStart), length - (index - inStart) - 1);
34 
35         return root;    
36         
37     }
38 
39     public int findIndex(int[] inorder, int val) {
40         for (int i = 0; i < inorder.length; i++) {
41             if (inorder[i] == val) {
42                 return i;
43             }
44         }
45         return -1;
46     }
47 }

 

 
 

Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5652021.html

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