zoukankan      html  css  js  c++  java
  • 剑指offer--重建二叉树

    题目 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
    思路 先画图 分析在二叉树的前序遍历序列中,第一个数字总是树的根节点的值。但在中序遍历中,根节点的值在序列的中间,左子树的节点的值位于根节点的值得左边,而右子树的节点的值位于根节点的值的右边。
    自己写的low代码

    /**
     * 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(pre==null||pre.length==0||in ==null||in.length==0) {
    	        	return  null;
    	        }
    	        TreeNode root = new TreeNode(pre[0]);
    	        int flag = -1;
    	        for(int i=0;i<in.length;i++) {
    	        	if(in[i]==root.val) {
    	        		flag = i;
    	        		break;
    	        	}
    	        }
    	        int[] preLeft = new int[flag];
    	        int[] preRight = new int[in.length-flag-1];
    	        int[] inLeft = new int[flag];
    	        int[] inRight =new int[in.length-flag -1];
    	    
    	        for(int i=1;i<=flag;i++) {
    	        	preLeft[i-1]=pre[i];
    	        }
    	        for(int i=flag+1;i<in.length;i++) {
    	        	preRight[i-flag-1]=pre[i];
    	        }
    	        for(int i=0;i<flag;i++) {
    	        	inLeft[i]=in[i];
    	        }
    	        for(int i=flag+1;i<in.length;i++) {
    	        	inRight[i-flag-1]=in[i];
    	        }
    	       root.left =  reConstructBinaryTree(preLeft,inLeft);
    	        root.right =reConstructBinaryTree(preRight,inRight);
    	        return root;
    	    }
       
    }
    
    多思考,多尝试。
  • 相关阅读:
    mysql uodate 报错 You can't specify target table '**' for update in FROM clause
    设置mysql InnoDB存储引擎下取消自动提交事务
    SQL插入数据--数据中的某一列来自本表中的数据
    服务器部署静态页面
    json 和 jsonp
    Git 回滚
    java 自定义注解
    java BlockingQueque的多种实现
    java 多线程之ReentrantLock与condition
    storm 架构原理
  • 原文地址:https://www.cnblogs.com/LynnMin/p/9388257.html
Copyright © 2011-2022 走看看