• 重建二叉树-剑指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; }
    }
  • 相关阅读:
    Oracle 删除某个用户下的对象
    解决11g导出时,空表不能导出问题
    Oracle常用sql
    Oracle 创建表空间和用户
    chapter4.1、函数,参数
    chapter3.6、标准库datetime
    chapter3.5内建函数
    简单选择排序和二元选择排序
    chapter3.4解析式、生成器
    列表解析练习
  • 原文地址:https://www.cnblogs.com/rosending/p/5608577.html
Copyright © 2020-2023  润新知