Construct Binary Tree from Inorder and Postorder Traversal
来源:互联网 发布:尚硅谷 java视频 编辑:程序博客网 时间:2024/06/11 10:27
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路:
inorder: left, current, right;
postorder, left, right, current;
postorder最后一个是current, 然后在inorder中搜索current index,然后左边的是left,右边的是right。算出左边的size之后,计算postorder的left,right index;
/** * 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[] inorder, int[] postorder) { if(inorder == null || postorder == null || inorder.length != postorder.length) return null; return build(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1); } public TreeNode build(int[] inorder, int istart, int iend, int[] postorder, int pstart, int pend) { if(istart> iend || pstart>pend){ return null; } TreeNode node = new TreeNode(postorder[pend]); int index = 0; for(int i=istart; i<=iend;i++){ if(inorder[i] == postorder[pend]){ index = i; break; } } node.left = build(inorder, istart, index-1, postorder, pstart, pstart+index-istart-1); node.right = build(inorder, index+1, iend, postorder, pstart+index-istart, pend-1); return node; } }
0 0
- *(leetcode) Construct Binary Tree from Inorder and Postorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 110: Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- Object-c入门笔记
- 键盘记录及自动发送VC++实现
- c#线程间传递参数详解
- 10061 - How many zero's and how many digits ?
- gettimeofday/settimeofday
- Construct Binary Tree from Inorder and Postorder Traversal
- Spring 3.1之无web.xml式 基于代码配置的servlet3.0应用
- Java是解释型语言还是编译型语言
- C#值类型和引用类型
- OpenGL学习三十四:剪裁区域和TGA图像文件的加载
- 黑马程序员---Runtime类
- Linux驱动开发学习的一些必要步骤
- vpn 技术
- 递归入门