Construct Binary Tree from Preorder and Inorder Traversal - Leetcode
来源:互联网 发布:淘宝扣分清零时间 编辑:程序博客网 时间:2024/05/19 18:13
/** * 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) { return buildTreeHelper(preorder, 0 ,preorder.length-1, inorder, 0, inorder.length-1); } private TreeNode buildTreeHelper(int[] pre, int pre_start, int pre_end, int[] in, int in_start, int in_end){ if(in_start > in_end || pre_start > pre_end) return null; int root_val= pre[pre_start]; int root_id=0; for(int i=in_start; i<=in_end; i++){ if(in[i] == root_val){ root_id = i; break; } } int distance = root_id-in_start; TreeNode root = new TreeNode(root_val); root.left = buildTreeHelper(pre, pre_start+1, pre_start+distance, in, in_start, root_id-1); root.right = buildTreeHelper(pre, pre_start+distance+1, pre_end, in, root_id+1, in_end); return root; } }
1)找到根节点,2)求出左子树的个数,逐个深入扩展左根节点,右根节点。
*题目中的特征是:
先序遍历:<span style="background-color: rgb(255, 102, 102);">中</span>左右
中序遍历:左<span style="background-color: rgb(255, 102, 102);">中</span>右
后序遍历:左右<span style="background-color: rgb(255, 102, 102);">中</span>
0 0
- *(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
- [leetCode] Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode] Construct Binary Tree from Preorder and Inorder Traversal
- 文件夹操作
- C# 打开外部文件
- c# 后台程序
- C# 中的字体
- User Define Message
- Construct Binary Tree from Preorder and Inorder Traversal - Leetcode
- VMware虚拟机关闭后托盘运行设置
- 读写操作,文件和注册表
- C# WinForm构架下的DirectX框架
- C#控件中使用DirectX
- 世界,观察和投影变换
- 十二五中国电信宽带战略解析(四):主导与包容
- 3D字体
- 辛星浅析Redis中的字符串类型