LeetCode-树-简单-108-110-111

108、将有序数组转化为二叉搜索树

  给你一个整数数组 nums ,其中元素已经按升序排列,请你将其转换为一棵高度平衡二叉搜索树。(高度平衡二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树。

  个人分析:一个数组按照升序排列,其实就是一棵二叉搜索树进行中序遍历序列。仅知道中序遍历序列不能唯一确定一棵二叉树,加上高度平衡这个条件也不能唯一确定,所以一题多解。为了保证平衡,就要保证根一定是升序序列的中间位置的数进行递归排列。代码如下:

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return sort(nums,0,nums.length-1);
    }

    public TreeNode sort(int[] nums,int low,int high) {
        //递归出口
        if(low>high) {
            return null;
        }
        //防止溢出
        int mid = low + (high-low)/2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = sort(nums,low,mid-1);
        root.right = sort(nums,mid+1,high);

        return root;

    }

其中寻找中间位置的数使用 int mid = low + (high-low)/2; 而不是用 int mid = (low +high)/2; 是为了防止int数值溢出。

110、判断是否为平衡二叉树

  给定一个二叉树,判断它是否是高度平衡的二叉树。(本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。

  个人分析:获得左子树和右子树的最大深度,然后比较深度差是否不超过1。

class Solution {
    public boolean isBalanced(TreeNode root) {

        //这个递归根据深度判断是否平衡
        if(root==null){
            return true;
        }
        if(Math.abs(maxDepth(root.left)-maxDepth(root.right))>1){
            return false;
        }

        return isBalanced(root.left) && isBalanced(root.right);

    }

    public int maxDepth(TreeNode root){
        //递归退出条件
        if(root==null){
            return 0;
        }
        return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
    }
}

111、二叉树的最小深度

  给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

  个人分析:求最小深度其实和求最大深度差不多,不过需要注意的是,null节点构不成子树。

class Solution {
    public int minDepth(TreeNode root) {

        //树本身为空
        if(root == null){
            return 0;
        }
        // //判断左子树为空右子树不为空
        // if(root.left==null && root.right!=null){
        //     return 1+minDepth(root.right);
        // }
        // //判断右子树为空左子树不为空
        // if(root.left!=null && root.right==null){
        //     return 1+minDepth(root.left);
        // }
        // return Math.min(minDepth(root.left),minDepth(root.right))+1;
        int lMinDepth = minDepth(root.left);
        int rMinDepth = minDepth(root.right);

        return root.left==null || root.right==null ? lMinDepth + rMinDepth + 1 : Math.min(lMinDepth,rMinDepth)+1;
        

    }

}
原文地址:https://www.cnblogs.com/YXSZ/p/14583843.html