06 重建二叉树
来源:互联网 发布:智能电视看电影软件 编辑:程序博客网 时间:2024/05/18 03:21
描述:
分析:
实现代码:
class Node{ int val; Node left; Node right; public Node(int val) { // TODO Auto-generated constructor stub this.val=val; }}public class MyCreateBinaryTree { static boolean valid=true; //是否为有效输入 public static void main(String[] args) { // TODO Auto-generated method stub int pre[]={1,2,4,7,3,5,6,8}; int in[]={4,7,2,1,5,3,8,6}; Node root=recreateBinaryTree(pre,in); if (valid) { display (root); }else { System.out.println("invalid input"); } } private static void display(Node root) { // TODO Auto-generated method stub if (root!=null) { System.out.print(root.val+" "); display(root.left); display(root.right); } } private static Node recreateBinaryTree(int[] pre, int[] in) { // TODO Auto-generated method stub Node root=createRecursive(pre,0,pre.length-1,in,0,in.length-1); return root; } private static Node createRecursive(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) { // TODO Auto-generated method stub if (pre==null||in==null) { valid=false; return null; } Node root=new Node(pre[startPre]); int rootInorder=startIn; //在中序遍历中找到根节点的位置 while (rootInorder<=endIn&&in[rootInorder]!=root.val) { rootInorder++; } if (rootInorder>endIn) { valid=false; return null; } int leftLength=rootInorder-startIn; if (leftLength>0) {//如果存在左子树 root.left=createRecursive(pre,startPre+1,startPre+leftLength,in,startIn,rootInorder-1); } if (leftLength<endPre-startPre) {//如果存在右子树 root.right=createRecursive(pre, startPre+leftLength+1, endPre, in, rootInorder+1, endIn); } return root; }}
测试结果:
这个程序处理了不合法的输入,亲可以试试哟!
0 0
- 06 重建二叉树
- 重建二叉树06
- 06_ConstructBinaryTree重建二叉树
- 06_重建二叉树
- 剑指offer 06:重建二叉树
- 剑指offer 06 重建二叉树
- 3.9重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 二叉树的重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- C语言文件操作之----文件的读写
- C# 线程同步
- 点击按扭后显示DIV,当然这个DIV 就显示在按扭旁边,当鼠标移动到DIV上时无变化,当鼠标移出DIV的时候,让DIV隐藏
- JS-正则表达式4
- jquery移动元素位置
- 06 重建二叉树
- HTML5笔记二:历史管理history
- AFNetworking3.0 GET/POST 以及上传(多)文件,下载文件
- 非正常关机,oracle启动报错,要打开数据库则必须使用 RESETLOGS 或 NORESETLOGS 选项
- 基于Scrapy框架的python网络爬虫学习(2)
- 第二次考试 (图论)第四题 货车运输
- 韩寒的博客文章---爬虫2
- 如何分析CoreDump文件
- Java - 99乘法表