经典:Construct Binary Tree from Preorder and Inorder Traversal:由先序中序构建二叉树
2018-01-22 16:17
459 查看
Given preorder and inorder traversal of a tree, construct the binary tree.
思路:手动模拟的时候,也是递归的重复。所以成序也是递归。为了减少重复时间,实现计算好中序中各个元素对应的下标位置。难点在于计算右子树时,需要计算偏移量。
这道题是必须会的一道题,非常非常的经典!
思路:手动模拟的时候,也是递归的重复。所以成序也是递归。为了减少重复时间,实现计算好中序中各个元素对应的下标位置。难点在于计算右子树时,需要计算偏移量。
这道题是必须会的一道题,非常非常的经典!
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode dfs(int prestart,int instart,int inend,int[] preorder,int[] inorder,HashMap<Integer,Integer> map){ if(prestart>= preorder.length||instart >= inorder.length||instart > inend ) return null; TreeNode n = new TreeNode(preorder[prestart]); n.left = dfs(prestart+1,instart,map.get(preorder[prestart])-1,preorder,inorder,map); n.right = dfs(prestart + map.get(preorder[prestart]) - instart +1,map.get(preorder[prestart]) + 1,inend,preorder ,inorder,map); return n; } public TreeNode buildTree(int[] preorder, int[] inorder) { HashMap map = new HashMap<Integer,Integer>(); for(int i = 0;i<inorder.length;i++){ map.put(inorder[i],i); } TreeNode root = dfs(0,0,inorder.length,preorder,inorder,map); return root; } }
相关文章推荐
- LeetCode-105:Construct Binary Tree from Preorder and Inorder Traversal (利用先序和中序遍历构建二叉树) -- medium
- 【构建二叉树】01根据前序和中序序列构造二叉树【Construct Binary Tree from Preorder and Inorder Traversal】
- [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal 由先序和中序遍历建立二叉树
- Construct Binary Tree from Preorder and Inorder Traversal 前序和中序重建二叉树
- 【二叉树经典问题】105. Construct Binary Tree from Preorder and Inorder Traversal
- [LintCode] 前序遍历和中序遍历树构造二叉树 Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode:105_Construct Binary Tree from Preorder and Inorder Traversal | 根据前序和中序遍历构建二叉树 | Medium
- 【LeetCode-面试算法经典-Java实现】【105-Construct Binary Tree from Preorder and Inorder Traversal(构造二叉树)】
- LeetCode-106:Construct Binary Tree from Inorder and Postorder Traversal (利用中序和后序遍历构建二叉树) -- medium
- LeetCode: 106_Construct Binary Tree from Inorder and Postorder Traversal | 根据中序和后序遍历构建二叉树 | Medium
- 5.2.1—二叉树的构建—Construct Binary Tree from Preorder and Inorder Traversal
- LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal (用先序和中序树遍历来建立二叉树)
- 【LeetCode笔记】Construct Binary Tree from Preorder and Inorder Traversal 前序、中序还原二叉树
- 105. Construct Binary Tree from Preorder and Inorder Traversal,前序+中序 构建 树
- 【构建二叉树】02根据中序和后序序列构造二叉树【Construct Binary Tree from Inorder and Postorder Traversal】
- 105\106. Construct Binary Tree from Inorder and Postorder\Preorder Traversal&重建二叉树
- Construct Binary Tree from Preorder and Inorder Traversal (给出前序中序求二叉树)
- <leetcode> 105. Construct Binary Tree from Preorder and Inorder Traversal 重建二叉树
- 根据前序和中序序列重建二叉树 Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal ——通过中序、后序遍历得到二叉树