leetcode_middle_95_105. Construct Binary Tree from Preorder and Inorder Traversal
来源:互联网 发布:淘宝联盟无法注册 编辑:程序博客网 时间:2024/05/18 22:18
题意:
给一个二叉树的前序遍历和中序遍历结果,构造出这棵树。
分析:
分析同上一篇。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length==0 || inorder.length==0) return null; return helper(preorder, inorder, 0, 0, inorder.length-1); } private TreeNode helper(int[] preorder, int[] inorder, int rootindex, int start, int end){ if(start > end){ return null; } int rootval = preorder[rootindex]; TreeNode root = new TreeNode(rootval); int index = findRootInInorder(rootval, inorder, start, end); int leftsize = index - start; root.left = helper(preorder, inorder, rootindex+1, start, index-1); root.right = helper(preorder, inorder, rootindex+1+leftsize, index+1, end); return root; } private int findRootInInorder(int rootval, int[] inorder, int start, int end){ for(int i=start; i<=end; i++){ if(inorder[i] == rootval){ return i; } } return -1; } }
0 0
- leetcode_middle_95_105. 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
- Construct Binary Tree from Preorder and Inorder Traversal & Construct Binary Tree from Inorder and P
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal
- 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
- Construct Binary Tree from Preorder and Inorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- [LeetCode]Construct Binary Tree from Preorder and Inorder Traversal
- 多项式乘法与加法运算(链表实现)
- spring boot应用启动原理分析
- 华为oj初级 放苹果
- HTTP协议知识重点
- cer证书转换.p12文件
- leetcode_middle_95_105. Construct Binary Tree from Preorder and Inorder Traversal
- JDBC连接mysql数据库
- spark数据倾斜调优(二)
- 在linux下为mysql创建新的用户
- Android Studio 断点调试Android源码的配置方法
- Linux Kernel设备驱动模型之驱动探测设备
- Linux Kernel设备驱动模型之设备绑定驱动
- 在iframe中寻找iframe父类中的元素
- CSS颜色渐变