106. Construct Binary Tree from Inorder and Postorder Traversal
来源:互联网 发布:php自动跳转页面 编辑:程序博客网 时间:2024/06/05 23:59
Given inorder and postorder traversal of a tree, construct the binary tree.
分析: 中序是左中右,后序是左右中,构建一棵树最重要的是找到其根节点,即中,因此以后序的最后一项开始遍历,然后以根节点的值在中序序列中寻找,若找到记录其位置,其位置左边的是当前根节点的左子树,其右边的则是其右子树。依次遍历即可。
code:
<span style="font-size:14px;">/** * 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 m=inorder.length; int n=postorder.length; if(m!=n||m==0) return null; return treeHelp(inorder,postorder,0,m-1,0,n-1); } public TreeNode treeHelp(int[] inorder,int[] postorder,int s1,int e1,int s2,int e2){ if(e2<s2) return null; TreeNode root=new TreeNode(postorder[e2]); int i=e1; for(;i>=s1;i--){ if(inorder[i]==postorder[e2]) break; } root.right=treeHelp(inorder,postorder,i+1,e1,e2-e1+i,e2-1); root.left=treeHelp(inorder,postorder,s1,i-1,s2,e2-e1+i-1); return root; }}</span>
0 0
- 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
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode#106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode *** 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- PAT测试1001 害死人不偿命的(3n+1)猜想 java实现
- Hive基本使用——命令行
- Ubuntu-server 下Apache2 配置.htaccess 隐藏thinkPHP项目index.php
- 易语言使用LhSocket5Net创建Socket5服务器
- 学习笔记
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 百度笔试--计算机视觉算法工程师
- 279. Perfect Squares
- (新规)最高法、最高检、公安部《关于电子数据收集提取判断的规定》(2016年10月1日施行)
- Android Studio鼠标悬停显示注释
- 形参个数可变的方法
- 黑科技
- JDBC连接数据库的步骤
- linux网络编程之socket(九):使用select函数改进客户端/服务器端程序