[leetcode-106]Construct Binary Tree from Inorder and Postorder Traversal(java)
来源:互联网 发布:域名添加白名单 编辑:程序博客网 时间:2024/05/22 16:02
问题描述:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
分析:要构造一个生成树,必须要有一个中序遍历,还要有一个前序或者后序遍历(否则找不到左子树和右子树)。这里与先序遍历相同,也是先确定根节点的位置。然后再递归下去。
代码如下:364ms
/** * 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) { int length = inorder.length; if(length<=0) return null; int rootVal = postorder[length-1]; int point; for(point = 0;point<length;point++){ if(inorder[point] == rootVal) break; } int[] leftInOrder = Arrays.copyOfRange(inorder,0,point); int[] rightInOrder = Arrays.copyOfRange(inorder,point+1,length); int[] leftPostOrder = Arrays.copyOfRange(postorder,0,point); int[] rightPostOrder = Arrays.copyOfRange(postorder,point,length-1); TreeNode root = new TreeNode(rootVal); root.left = buildTree(leftInOrder,leftPostOrder); root.right = buildTree(rightInOrder,rightPostOrder); return root; }}
0 0
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal (Java)
- [LeetCode][Java] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal [106]
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode 106] Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode 106]Construct Binary Tree from Inorder and Postorder Traversal
- leetcode || 106、Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal - LeetCode 106
- LeetCode 106:Construct Binary Tree from Postorder and Inorder Traversal
- LeetCode---(106)Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode(106) Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode #106 Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 106: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
- 【LEETCODE】106-Construct Binary Tree from Inorder and Postorder Traversal
- 集成ACEGI 进行权限控制
- Activity 学习
- 将activity铺满整个屏幕(去掉title以及状态栏)
- 对Powerdesigner中的Cardinality基数理解
- iOS安全系列之一:HTTPS
- [leetcode-106]Construct Binary Tree from Inorder and Postorder Traversal(java)
- hdoj1233还是畅通工程
- 时光轴一之listView实现时光轴效果
- LeetCode-30 Substring with Concatenation of All Words
- 在非Spring容器中使用注入
- POST与GET的差异
- 【Android UI】Fragment+ViewPage实现滑动
- achartengine刷新数据
- Python中逗号的作用