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

    重建二叉树

    题目描述

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

    思路

    1. 先序遍历的第一个节点是中序遍历的根节点
    2. 从中序遍历中找先序遍历的那个根节点,然后切开左右子树,用递归函数分别构造左右子树

    代码

    public class Solution04 {
    	// 重建二叉树
        public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
            if (pre == null || in == null) {
            	return null;
            }
            return ConstructCore(pre, 0, pre.length -1, in, 0, in.length -1);
        }
    	public TreeNode ConstructCore(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) {
    		int rootValue = pre[startPre];
    		TreeNode root = new TreeNode(rootValue);
    		root.left = null;
    		root.right = null;
    		
    		if (startPre == endPre && startIn == endIn) {
    			return root;
    		}
    		
    		int leftLen = 0;
    		int rootIn = startIn;
    		while (startIn <= endIn && in[startIn] != rootValue) {
    			startIn++;
    			leftLen++;
    		}
    		int leftPreEnd = startPre + leftLen;
    		if (leftLen > 0) {
    			// 构建左子树
    			root.left = ConstructCore(pre, startPre + 1, leftPreEnd, in, rootIn, startIn - 1);
    		}
    		if (leftLen < endPre - startPre) {
    			//构建右子树
    			root.right = ConstructCore(pre, leftPreEnd + 1, endPre, in, startIn + 1, endIn);
    		}
    		return root;
    	}
    	
    
    
    }
    class TreeNode {
    	int val;
    	TreeNode left;
    	TreeNode right;
    	TreeNode(int x) { val = x; }
    }
  • 相关阅读:
    SDN概述
    Linux企业运维人员必备150个命令汇总
    自动化运维工具puppet详解(二)
    自动化运维工具puppet详解(一)
    自动化运维工具[ansible详解三]
    ansible 常用模块
    自动化运维工具【ansible详解 二】
    A. Cinema Line
    A. Wrong Subtraction
    A. The number of positions
  • 原文地址:https://www.cnblogs.com/rosending/p/5608577.html
Copyright © 2011-2022 走看看