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;
        }
    }
  • 相关阅读:
    uoj35 后缀排序
    bzoj1026windy数
    poj2761 feed the dog
    codevs2875RY哥查字典
    bzoj1683[Usaco2005 Nov]City skyline 城市地平线
    codevs2464超级麻将
    初赛乱记
    让NOI Linux变得可用
    [HAOI2015] 按位或
    一句话CF
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7207748.html
Copyright © 2011-2022 走看看