105. Construct Binary Tree from Preorder and Inorder Traversal

Posted panini

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了105. Construct Binary Tree from Preorder and Inorder Traversal相关的知识,希望对你有一定的参考价值。

题目:

Given preorder and inorder 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-preorder-and-inorder-traversal/

6/7/2017

抄别人的答案

21ms, 29%

注意的地方

1. 题目中给出了节点没有重复值,所以可以利用第17行开始的循环

2. 第4行和第10行应该用exception,但是目前并不熟悉

3. 注意第24,25行的各个下标,preorder时候左子树最后一个节点的下一个就是右子树第一个节点,而inorder时候中间还隔着一个root节点

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

别人的做法:

iterative:尚未看懂

https://discuss.leetcode.com/topic/795/the-iterative-solution-is-easier-than-you-think

另一个没看懂的答案

https://discuss.leetcode.com/topic/16221/simple-o-n-without-map

 1 def buildTree(self, preorder, inorder):
 2     def build(stop):
 3         if inorder and inorder[-1] != stop:
 4             root = TreeNode(preorder.pop())
 5             root.left = build(root.val)
 6             inorder.pop()
 7             root.right = build(stop)
 8             return root
 9     preorder.reverse()
10     inorder.reverse()
11     return build(None)

更多讨论

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

 

以上是关于105. Construct Binary Tree from Preorder and Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

105.Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal