重建二叉树
来源:互联网 发布:win10如何优化虚拟机 编辑:程序博客网 时间:2024/06/09 22:29
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路
首先通过前序遍历确定根节点,在中序遍历中确定左右分支。如上面的例子,通过前序遍历的第一个节点知道根节点是1,通过中序遍历知道左分支是4,7,2右分支是5,3,8,6。接着递归调用,确定左分支的根节点和右分支的根节点。
关键是对前序遍历和后序遍历确定左右分支的范围。
class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}public class chongjianerchashu { public TreeNode buildTree(int[] pre, int[] in, int preStart, int preEnd, int inStart, int inEnd) { int rootIndex = 0; for (int i = inStart; i <= inEnd; i++) { if (in[i] == pre[preStart]) { rootIndex = i; break; } } TreeNode node = new TreeNode(in[rootIndex]); int lDis = rootIndex - inStart;// 元素个数 int rDis = inEnd - rootIndex; if (lDis > 0) node.left = buildTree(pre, in, preStart + 1, preStart + lDis, inStart, rootIndex - 1); if (rDis > 0) node.right = buildTree(pre, in, preEnd - rDis + 1, preEnd, rootIndex + 1, inEnd); return node; } public TreeNode reConstructBinaryTree(int[] pre, int[] in) { if (pre == null || in == null || pre.length == 0 || in.length == 0 || pre.length != in.length) return null; return buildTree(pre, in, 0, pre.length - 1, 0, in.length - 1); } public static void main(String[] args) { new chongjianerchashu().reConstructBinaryTree(new int[] { 1, 2, 4, 7, 3, 5, 6, 8 }, new int[] { 4, 7, 2, 1, 5, 3, 8, 6 }); }}
阅读全文
0 0
- 3.9重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 二叉树的重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- .json.JSONException: java.lang.NoSuchMethodException: bean.Equipmentplan.<init>()
- Android中Adapter的notifyDataSetInvalidated()和notifyDataSetChanged()的区别
- Android 重写系统Crash处理类,保存Crash信息到SD卡 和 完美退出程序的方法
- C语言中"."和"->"的区别
- 复盘_8月(第4周工作复盘)
- 重建二叉树
- Xcode 查看运行时ViewController结构
- Android 分享一个SharedPreferences的工具类,方便保存数据
- 神经网络学习笔记
- hdu 6158 The Designer 计算几何之圆反演 2017中国大学生程序设计竞赛
- MongoDB集群间环境迁移
- python io流(8)
- Struts2的访问路径一:固定访问路径
- 交换排序-快速排序