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;
    	    }
       
    }
    
    多思考,多尝试。
  • 相关阅读:
    bzoj 5092: [Lydsy1711月赛]分割序列
    bzoj1173: [Balkan2007]Point
    bzoj1536: [POI2005]Akc- Special Forces Manoeuvres
    bzoj2178: 圆的面积并
    bzoj1043 下落的圆盘
    bzoj2674 Attack
    bzoj1201: [HNOI2005]数三角形
    bzoj3135: [Baltic2013]pipesd
    bzoj1760 [Baltic2009]Triangulation
    bzoj3136
  • 原文地址:https://www.cnblogs.com/LynnMin/p/9388257.html
Copyright © 2011-2022 走看看