LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告

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.

 

Hide Tags
 Tree Array Depth-first Search
 

SOLUTION 1:

使用递归的思想,先找到根节点(它就是post order最后一个),然后再在inorder中找到它,以确定左子树的node个数。
然后分别确定左子树右子树的左右边界
例子:
{4, 5, 2, 7, 8, 1, 3}这树的
inorder: 7 5 8 | 4 | 1 2 3
post: 7 8 5 | 1 3 2 | 4
以上我们可以看到左右子树的划分关系。
 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         if (inorder == null || postorder == null) {
13             return null;
14         }
15         
16         return dfs(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
17     }
18     
19     public TreeNode dfs(int[] inorder, int[] postorder, int inL, int inR, int postL, int postR) {
20         if (inL > inR) {
21             return null;
22         }
23         
24         // create the root node.
25         TreeNode root = new TreeNode(postorder[postR]);
26         
27         // find the position of the root node in the inorder traversal.
28         int pos = 0;
29         for (; pos <= inR; pos++) {
30             if (inorder[pos] == postorder[postR]) {
31                 break;
32             }
33         }
34         
35         int leftNum = pos - inL;
36         
37         root.left = dfs(inorder, postorder, inL, pos - 1, postL, postL + leftNum - 1);
38         root.right = dfs(inorder, postorder, pos + 1, inR, postL + leftNum, postR - 1);
39         
40         return root;
41     }
42 }
View Code

代码: https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/BuildTree2.java

posted on 2015-01-03 16:36  Yu's Garden  阅读(376)  评论(0编辑  收藏  举报

导航