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.

SOLUTION 1:

1. Find the root node from the preorder.(it is the first node.)

2. Try to find the position of the root in the inorder. Then we can get the number of nodes in the left tree.

3. 递归调用,构造左子树和右子树。

例子:

Pre:       4 2 1 3 6 5 7

Inorder: 1 2 3 4 5 6 7

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
// bug 3: consider when length is 0.
if (preorder == null || inorder == null || preorder.length == 0 || preorder.length != inorder.length) {
return null;
} // bug 4: end index is length - 1.
return buildTree(preorder, inorder, 0, preorder.length - 1, 0, preorder.length - 1);
} public TreeNode buildTree(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
// base case;
if (preStart > preEnd) {
return null;
} int rootVal = preorder[preStart];
TreeNode root = new TreeNode(rootVal); int pos = findTarget(inorder, rootVal, inStart, inEnd); // bug 5: left number is pos - instart can't add 1
int leftNum = pos - inStart; root.left = buildTree(preorder, inorder, preStart + 1, preStart + leftNum, inStart, pos - 1);
root.right = buildTree(preorder, inorder, preStart + leftNum + 1, preEnd, pos + 1, inEnd); return root;
} // bug 1: return type required.
// bug 2: this is not a bst. can't use binary search.
public int findTarget(int[] A, int target, int start, int end) {
for (int i = start; i <= end; i++) {
if (target == A[i]) {
return i;
}
} return -1;
}
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/BuildTree.java

最新文章

  1. Webform(六)——登录状态保持(Cookies内置对象)
  2. Lua 性能相关笔记
  3. HtmlAgilityPack中通过sibling才能得到对应的InnerText和form,option等tag的子节点
  4. Android应用权限管理总结
  5. 2016 - 1 - 20 runloop学习(2)
  6. BZOJ 1010 玩具装箱
  7. ASP常用函数表
  8. dom4j 的小小测试
  9. ZeroMemory
  10. apache日志介绍
  11. Linux企业级项目实践之网络爬虫(14)——使用正则表达式抽取HTML正文和URL
  12. Linux上MongoDB的安装与配置
  13. STL迭代器与部分算法学习笔记
  14. apache动态添加模块
  15. Servlet 易错点和注意点
  16. POSIX共享内存
  17. splay详解(三)
  18. mysql 通过测试&#39;for update&#39;,深入了解行锁、表锁、索引
  19. maven+springmvc项目启动时,request mapping not found……
  20. udev example -- detect usb and write test file

热门文章

  1. Python函数的静态变量
  2. 【总结 】550,535,553 Mail from must equal authorized user— jenkins(hudson) email163邮箱和26邮箱成功配置总结
  3. placement new 笔记
  4. 树莓派进阶之路 (025) - ubuntu下使用VNC连接树莓派raspberry(转)
  5. block(九)Block 和 Delegate 的使用比较
  6. 免费的UI素材准备
  7. 站在.NET的角度学安卓的草民笔记1
  8. mac mini 制作fusion drive 的方法
  9. 转: FFmpeg功能命令汇总
  10. Knockout: 让ViewModel从htm中剥离出去。