重建二叉树06
来源:互联网 发布:古装淘宝 编辑:程序博客网 时间:2024/06/05 22:30
class Node{int val;Node left;Node right;public Node(int val) {// TODO Auto-generated constructor stubthis.val=val;}}public class MyCreateBinaryTree { staticboolean valid=true; //是否为有效输入public static void main(String[] args) {// TODO Auto-generated method stubint 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 stubif (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 stubNode 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 stubif (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重建二叉树
- 重建二叉树
- 二叉树重建
- 二叉树重建
- 二叉树的重建
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 重建二叉树
- 简单背包练习——分组背包
- AS出现Unsupported major.minor version 52.0
- 关于android的mk文件的一些见解
- 希尔排序 Java实现
- tomcat如何配置环境变量
- 重建二叉树06
- 关于leetcode Minimum Window Substring的思考
- Nginx作为反向代理
- numpy-线性代数
- struts2中的文本框不可编辑
- RS232和RS485、TTL有什么区别?
- CCF软件能力认证考试模拟题 ISBN号码
- 黑板客 -- 爬虫闯关 -- 关卡02
- PHP json_decode 精度丢失问题!