LeetCode刷题Easy篇Convert Sorted Array to Binary Search Tree

题目

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

简单说就是把一个有序数组转为平衡二叉树。常见的二叉查找树,有可能退化为链表,时间复杂度从logn将退化为O(n),所以实际应用中的AVL,红黑树都是平衡二叉树

我的尝试

其实是构造一个平衡二叉树,无非是节点值已经指定,没有思路处理这类问题,看了disscuss之后,按照高手的思路自己写了一下,看看是否可以一点就通。

先梳理一下思路,二叉平衡时,首先满足二叉树的条件,左侧小于根节点,右侧大于根节点。因为数组有序,其实我们寻找中间的节点作为根节点就可以。如何保证平衡呢?每次都是中间元素作为根节点,所有左右节点数相差绝对值不会大于1.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==0) return null;
        int p=0;
        int q=nums.length;
        return createTree(nums,p,q);
    }
    public  TreeNode createTree(int[] nums,int p,int q){
        if(p>q){
            return null;
        }
        int mid=(p+q)/2;
        TreeNode  treeNode=new TreeNode(nums[mid]);
        treeNode.left=createTree(nums,0,mid-1);
        treeNode.right=createTree(nums,mid+1,nums.length);
        return treeNode;
        
    }
    
}

运行之后stackoverflow错误。递归调用createTree的入参写错了,修改后如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==0) return null;
        int p=0;
        int q=nums.length-1;
        return createTree(nums,p,q);
    }
    public  TreeNode createTree(int[] nums,int p,int q){
        if(p>q){
            return null;
        }
        int mid=(p+q)/2;
        TreeNode  treeNode=new TreeNode(nums[mid]);
        treeNode.left=createTree(nums,p,mid-1);
        treeNode.right=createTree(nums,mid+1,q);
        return treeNode;
        
    }
    
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/84787450
今日推荐