美文网首页
108. Convert Sorted Array to Bin

108. Convert Sorted Array to Bin

作者: liuhaohaohao | 来源:发表于2018-05-31 19:25 被阅读0次

    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
    

    二叉搜索树(BST)

    1. 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
    2. 若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
    3. 它是一棵空树或它的左右两个子树的高度差的绝对值不超过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) {
            TreeNode root = treeHelper(nums, 0, nums.length-1);
            return root;
        }
        public TreeNode treeHelper(int[] nums, int left, int right){
            if (left > right){
                return null;
            }
            int mid = (left + right)/2;
            TreeNode root = new TreeNode(nums[mid]);
            root.left = treeHelper(nums, left, mid - 1);
            root.right = treeHelper(nums, mid + 1, right);
            return root;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:108. Convert Sorted Array to Bin

          本文链接:https://www.haomeiwen.com/subject/klhcsftx.html