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

105. Construct Binary Tree from Preorder and Inorder Traversal

时间:2017-06-07 20:58:54      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:bsp   int   rsa   order   and   public   binary   iter   topic   

题目:

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

标签:bsp   int   rsa   order   and   public   binary   iter   topic   

原文地址:http://www.cnblogs.com/panini/p/6958817.html

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