106. 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.

链接:  http://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

6/7/2017

25ms, 17%

最后一点有些错误,照着别人的改了。

注意的地方:

1. 找Root从postorder最后面开始找

2. 左子树长度在inorder, postorder,以及preorder里都是一样的。且左子树所有节点在这三种遍历方式里都是连续的。所以可以通过第23行找到左子树长度,并且应用到postorder, preorder当中。

 1 public class Solution {
 2     public TreeNode buildTree(int[] inorder, int[] postorder) {
 3         if (inorder == null || postorder == null) {
 4             return null;
 5         }
 6         return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
 7     }
 8     private TreeNode buildTree(int[] inorder, int inLo, int inHi, int[] postorder, int postLo, int postHi) {
 9         if (inorder == null || postorder == null) {
10             return null;
11         }
12         if (inLo > inHi || postLo > postHi) {
13             return null;
14         }
15         TreeNode node = new TreeNode(postorder[postHi]);
16         int rootInorderIndex = 0;
17         for (int i = inLo; i <= inHi; i++) {
18             if (inorder[i] == node.val) {
19                 rootInorderIndex = i;
20                 break;
21             }
22         }
23         int leftTreeLength = rootInorderIndex - inLo;
24         node.left = buildTree(inorder, inLo, rootInorderIndex - 1, postorder, postLo, postLo + leftTreeLength - 1);
25         node.right = buildTree(inorder, rootInorderIndex + 1, inHi, postorder, postLo + leftTreeLength, postHi - 1);
26         return node;
27     }
28 }

别人的做法:

用stack没有递归的解法

https://discuss.leetcode.com/topic/4746/my-comprehension-of-o-n-solution-from-hongzhi

https://discuss.leetcode.com/topic/8207/java-iterative-solution-with-explanation

更多讨论

https://discuss.leetcode.com/category/114/construct-binary-tree-from-inorder-and-postorder-traversal

posted @ 2017-06-07 20:14  panini  阅读(167)  评论(0编辑  收藏  举报