[LeetCode][Java] Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:大数据徐子沛百度云 编辑:程序博客网 时间:2024/06/05 16:31
题目:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
题意:
给定一棵树的先序和中序遍历,构建这颗二叉树。
注意:
你可以假定这棵树中不存在重复。
算法分析:
* 中序序列和后序序列构造二叉树和此题算法是一样的
* 这里的区别是要从中序遍历和先序遍历中构造出树
* 只是现在取根是从前面取(因为先序遍历根是遍历的第一个元素)。
* 思想和代码基本都是差不多的,自然时间复杂度和空间复杂度也还是O(n)
AC代码:
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if(inorder==null || preorder==null || inorder.length==0 || preorder.length==0) return null; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0;i<inorder.length;i++) { map.put(inorder[i],i); } return helper(inorder,preorder,0,inorder.length-1, 0, preorder.length-1,map); } private TreeNode helper(int[] inorder, int[] preorder, int inL, int inR, int preL, int preR, HashMap<Integer, Integer> map) { if(inL>inR || preL>preR) return null; TreeNode root = new TreeNode(preorder[preL]); int index = map.get(root.val); root.left = helper(inorder,preorder,inL,index-1,preL+1,preR-(inR-index),map); root.right = helper(inorder,preorder,index+1,inR,preL+index-inL+1,preR,map); return root; }}</span>
0 0
- [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal (Java)
- [LeetCode][Java] Construct Binary Tree from Preorder and Inorder Traversal
- *(leetcode) Construct Binary Tree from Preorder and Inorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode][tree] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- [Leetcode] Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode Construct Binary Tree from Preorder and Inorder Traversal
- leetcode 109: Construct Binary Tree from Preorder and Inorder Traversal
- 【leetcode】Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode-Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode] Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode - Construct Binary Tree from Preorder and Inorder Traversal
- Single Number III
- day05--面向对象--各种类
- 文章标题
- C++静态成员变量和静态成员函数
- 如何在myeclipse中使用自己的tomcat
- [LeetCode][Java] Construct Binary Tree from Preorder and Inorder Traversal
- x86 INSTALL_FAILED_SHARED_USER_INCOMPATIBLE
- IT常用Terms
- ros创建package 总结
- hdu4135 co-prime(容斥原理)
- 防火墙修改
- C++中的四种强制类型转换
- Cookbook编写
- [DFS] AOJ 0033 Ball