剑指Offer-重建二叉树
来源:互联网 发布:php api 框架 编辑:程序博客网 时间:2024/05/04 11:16
重建二叉树
题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
解题思路:
(1)如果前序遍历为空或中序遍历为空或节点个数小于等于0,返回NULL。
(2)创建根节点。前序遍历的第一个数据就是根节点的数据,在中序遍历中找到根节点的位置,可分别得知左子树和右子树的前序和中序遍历序列,重建左右子树。
我的Java实现源代码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(null == pre || pre.length==0){ return null; } int treeLength = pre.length; TreeNode node = new TreeNode(pre[0]); int rootIndex = -1; for(int i = 0 ; i<in.length; i++){ if(node.val == in[i]){ rootIndex=i; break; } } if(rootIndex == -1){ return null; } //重建左子树 int []leftPre = new int[rootIndex]; for(int i = 1,j=0 ; i <= rootIndex; i++){ leftPre[j++] = pre[i]; } int []leftIn = new int[rootIndex]; for(int i = 0,j=0 ; i < rootIndex; i++){ leftIn[j++] = in[i]; } node.left = reConstructBinaryTree(leftPre,leftIn); //重建右子树 int []rightPre = new int[treeLength - rootIndex-1]; for(int i = rootIndex+1 ,j=0; i < treeLength; i++,j++){ rightPre[j] = pre[i]; } int []rightIn = new int[treeLength - rootIndex-1]; for(int i = rootIndex+1,j=0 ; i < treeLength; i++,j++){ rightIn[j] = in[i]; } node.right = reConstructBinaryTree(rightPre,rightIn); return node; }}
0 0
- [剑指offer]重建二叉树
- 【剑指offer】重建二叉树
- 剑指offer--重建二叉树
- 剑指offer---重建二叉树
- 剑指Offer-重建二叉树
- 剑指offer:重建二叉树
- 剑指offer-重建二叉树
- 《剑指offer》重建二叉树
- 【剑指Offer】重建二叉树
- 剑指offer-重建二叉树
- 《剑指offer》-重建二叉树
- 剑指offer 重建二叉树
- 剑指offer:重建二叉树
- 【剑指offer】重建二叉树
- 剑指offer 重建二叉树
- [剑指offer]重建二叉树
- 剑指offer--重建二叉树
- 《剑指offer》重建二叉树
- 剑指Offer-从头到尾打印链表
- 1302 The Snail【模拟】
- Python 日志(logging)模块
- Android 线程详解
- Walls(floyd POJ1161)
- 剑指Offer-重建二叉树
- DB2 存储过程的异常处理器类型有几种?
- JavaFX中javafx.concurrent.Task类的使用
- Terminal Access Controller Access-Control System
- 第50讲:Scala中Variance变化点及其在Spark中的应用源码解析学习笔记
- 剑指Offer-链表中倒数第k个结点
- 面试常见问题
- ztree 使用asp.net mvc异步动态获取数据
- 剑指Offer-合并两个排序的链表