zoukankan      html  css  js  c++  java
  • [LeetCode] 108. Convert Sorted Array to Binary Search Tree Java

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

    题意及分析:给出一个有序序列,构造一棵平衡二叉查找树。二叉查找树:对于任意一个节点,都有左子节点小于右节点;二叉平衡树:对于任意一个节点,左右子树的高度差不超过1。这里可以将序列的中点当做根节点,然后递归左右子序列。

    代码:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            return bulidTree(nums,0,nums.length-1);
        }
    
        public TreeNode bulidTree(int[] nums,int start,int end){
            if(start>end) return null;
            int mid = (start+end)/2;
            TreeNode root = new TreeNode(nums[mid]);
            root.left = bulidTree(nums,start,mid-1);
            root.right = bulidTree(nums,mid+1,end);
            return root;
        }
    }
  • 相关阅读:
    uva10256
    uva11168
    zoj2318
    hdu6121
    hdu6127
    bzoj3957: [WF2011]To Add or to Multiply
    bzoj4377: [POI2015]Kurs szybkiego czytania
    bzoj3137: [Baltic2013]tracks
    bzoj4069: [Apio2015]巴厘岛的雕塑
    bzoj4169: Lmc的游戏
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7207748.html
Copyright © 2011-2022 走看看