剑指offer-重建二叉树
来源:互联网 发布:手机淘宝改地址在哪里 编辑:程序博客网 时间:2024/04/29 07:54
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
题目分析
首先应该弄清楚前序遍历,中序遍历,后序遍历的遍历流程,然后应该明白树的递归定义:要么树为空,要么由根和零个或多个非空子树组成。那么,我们就可以用递归重建一棵二叉树。
import java.util.Arrays;public class 重建二叉树 { public static TreeNode reConstructBinaryTree(int[] pre, int[] in) { //首先找到根节点,前序遍历的第一个数是根节点上面的值 int rootData = pre[0]; TreeNode root = new TreeNode(rootData);// 找到跟节点 // 在中序遍历中找到rootData的位置 int rootinIndex = 0; int temp = in[rootinIndex]; while (rootinIndex < in.length && rootData != temp) { rootinIndex++; temp = in[rootinIndex]; } if (rootinIndex == in.length && rootData != in[rootinIndex - 1]) { throw new IllegalArgumentException("invalid input"); } // 如果有左孩子节点,那么中序遍历的rootData前面的数据都是左孩子节点上的,前序遍历的[1,rootinIndex]都是左孩子节点上的 if (rootinIndex > 0) { root.left = reConstructBinaryTree( Arrays.copyOfRange(pre, 1, rootinIndex + 1), Arrays.copyOfRange(in, 0, rootinIndex)); } // 如果有右孩子节点,那么中序遍历rootinIndex到最后都是右孩子节点上的,前序遍历的rootinIndex到最后也都是右孩子节点上的 if (rootinIndex < in.length - 1) { root.right = reConstructBinaryTree( Arrays.copyOfRange(pre, rootinIndex + 1, pre.length), Arrays.copyOfRange(in, rootinIndex + 1, in.length)); } return root; } public static void main(String[] args) { int[] preOrder = { 1, 2, 4, 7, 3, 5, 6, 8 }; int[] inOrder = { 4, 7, 2, 1, 5, 3, 8, 6 }; TreeNode root = reConstructBinaryTree(preOrder, inOrder); inOrder(root); System.out.println(); preOrder(root); System.out.println(); postOrder(root); } public static void preOrder(TreeNode n) { if (n != null) { System.out.print(n.val + ","); preOrder(n.left); preOrder(n.right); } } public static void inOrder(TreeNode n) { if (n != null) { inOrder(n.left); System.out.print(n.val + ","); inOrder(n.right); } } public static void postOrder(TreeNode n) { if (n != null) { postOrder(n.left); postOrder(n.right); System.out.print(n.val + ","); } }}class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
0 0
- [剑指offer]重建二叉树
- 【剑指offer】重建二叉树
- 剑指offer--重建二叉树
- 剑指offer---重建二叉树
- 剑指Offer-重建二叉树
- 剑指offer:重建二叉树
- 剑指offer-重建二叉树
- 《剑指offer》重建二叉树
- 【剑指Offer】重建二叉树
- 剑指offer-重建二叉树
- 《剑指offer》-重建二叉树
- 剑指offer 重建二叉树
- 剑指offer:重建二叉树
- 【剑指offer】重建二叉树
- 剑指offer 重建二叉树
- [剑指offer]重建二叉树
- 剑指offer--重建二叉树
- 《剑指offer》重建二叉树
- Android系统以及Activity启动讲解
- linux驱动中的platform总线架构(含具体IIC设备驱动)
- iOS - 高德地图(原生)
- 15_09_14 LinearLayout 布局 计算器示例
- bootstrap第四天
- 剑指offer-重建二叉树
- 在线调查工具serveymonkey
- 工作日志-2015/9/15-2015-9-21
- chmod每个代号代表权限
- HDU 5443 The Water Problem(水题 找区间最大值)——2015 ACM/ICPC Asia Regional Changchun Online
- 【C++】warning C4018: “<”: 有符号/无符号不匹配
- eclipse插件集合
- STL源码剖析 [容器](二十)[stl_hash_set.h]
- load与reload extj