剑指offer04--根据前序和中序构建二叉树
来源:互联网 发布:windows正在下载更新0 编辑:程序博客网 时间:2024/06/03 19:28
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
*假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
* 例如:前序遍历序列{ 1, 2, 4, 7, 3, 5, 6, 8}和
* 中序遍历序列{4, 7, 2, 1, 5, 3, 8,6},
*假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
* 例如:前序遍历序列{ 1, 2, 4, 7, 3, 5, 6, 8}和
* 中序遍历序列{4, 7, 2, 1, 5, 3, 8,6},
其中最重要的就是两句核心代码,理解起来还是有点难度的,但是多瞅几遍应也没有什么大的问题
/* * 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。 * 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 * 例如:前序遍历序列{ 1, 2, 4, 7, 3, 5, 6, 8}和 * 中序遍历序列{4, 7, 2, 1, 5, 3, 8,6}, * 重建出下图所示的二叉树并输出它的头结点。 */package 剑指offer; import java.util.*;public class Test06{public static void main(String args[]){ test1();}public static void printTree(BinaryTreeNode root){//中序遍历if(root != null){printTree(root.left);System.out.print(root.value+" ");printTree(root.right);}} // 普通二叉树 // 1 // / \ // 2 3 // / / \ // 4 5 6 // \ / // 7 8 public static void test1() { int[] preorder = {1, 2, 4, 7, 3, 5, 6, 8}; int[] inorder = {4, 7, 2, 1, 5, 3, 8, 6}; BinaryTreeNode root = construct(preorder, inorder); printTree(root); } public static class BinaryTreeNode{ // 定义二叉树结点 int value; BinaryTreeNode left; BinaryTreeNode right; } public static BinaryTreeNode construct(int preorder[], int inorder[]){ if(preorder == null || inorder == null || preorder.length != inorder.length){ return null; } return construct(preorder, 0, preorder.length - 1, inorder, 0, inorder.length -1); } public static BinaryTreeNode construct(int preorder[], int ps, int pe, int inorder[], int is, int ie){ if(ps > pe || is > ie){ return null; } int value = preorder[ps]; int index = is; while(index < ie && inorder[index] != value){ index++; if(index > ie){ throw new RuntimeException("Error"); } } BinaryTreeNode node = new BinaryTreeNode(); node.value = value; // 递归构建当前根结点的左子树,左子树的元素个数:index-is+1个 // 左子树对应的前序遍历的位置在[ps+1, ps+index-is] // 左子树对应的中序遍历的位置在[is, index-1] node.left = construct(preorder, ps + 1, ps + index - is, inorder, is, index - 1); // 递归构建当前根结点的右子树,右子树的元素个数:ie-index个 // 右子树对应的前序遍历的位置在[ps+index-is+1, pe] // 右子树对应的中序遍历的位置在[index+1, ie] node.right = construct(preorder, ps + index - is + 1, pe, inorder, index + 1, ie); return node; }}其中test1()是重写构建二叉树的函数体
注意细节,背诵优质代码
1 0
- 剑指offer04--根据前序和中序构建二叉树
- 根据前序和中序,构建二叉树
- 根据中序和前序遍历构建二叉树
- 根据前序和中序构建二叉树
- 剑指offer 面试题6 (根据前序和中序 构建二叉树)
- 根据二叉树的前序和中序构建二叉树
- 根据前序 中序 后序 构建二叉树
- 根据前序遍历,中序遍历构建二叉树
- 根据前序、中序构建二叉树
- 根据前序和后序构建二叉树
- 根据前序遍历和中序遍历构建二叉树
- Offer题6 根据前序和中序构建二叉树
- 根据中序遍历和前序遍历构建二叉树
- 面试题6:根据前序和中序序列构建二叉树(Leetcode-106)
- 二叉树系列——根据前序和中序、中序和后序构建二叉树
- 根据前序遍历和中序遍历构建二叉树以及根据中序遍历后序遍历构建二叉树
- 根据二叉树的前序遍历和中序遍历构建二叉树的c语言完整代码
- 根据树的后序和中序序列或者前序和中序序列构建二叉树,
- iOS 使用可缩放图像的自定义按钮
- 字符串按照字典序排序
- shelve模块
- 第10,11周 项目2(1)
- 304. Range Sum Query 2D - Immutable
- 剑指offer04--根据前序和中序构建二叉树
- Cocos2d-x中的坐标转换
- Fragment和Activity
- 关于获取手机Ram总内存的方法
- Leetcode Everyday: 88. Merge Sorted Array
- linux 重定向
- poj 1285 拓扑排序
- [ARM] Cortex-M Startup.s启动文件相关代码解释
- Hadoop介绍