zoukankan      html  css  js  c++  java
  • Leetcode: Convert Sorted Array to Binary Search Tree

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

    基本上一次过,要注意边界条件的问题:如果在recursion里有两个参数int begin, end, 递归写作recursion(num, mid+1, end), 因为+号的原因,递归中是会出现begin > end 的情况的,所以考虑初始条件的时候应该要考虑充分。

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public TreeNode sortedArrayToBST(int[] num) {
    12         if (num == null || num.length == 0) return null;
    13         return construct(num, 0, num.length - 1);
    14     }
    15     
    16     public TreeNode construct(int[] num, int begin, int end) {
    17         if (begin > end) return null; 
    19 int mid = (begin + end) / 2; 20 TreeNode root = new TreeNode(num[mid]); 21 root.left = construct(num, begin, mid-1); 22 root.right = construct(num, mid+1, end); 23 return root; 24 } 25 }
  • 相关阅读:
    layui 相关知识
    ideal debug 启动不起来
    删除命令 rm -rf maven-project-jxcg.zip 解压 unzip maven-project-jxcg.zip
    vsb 配置
    cmd dos
    switch
    Element UI 框架搭建
    mysql 远程连接设置
    YApi可视化接口管理平台 接口
    报403错误
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3746865.html
Copyright © 2011-2022 走看看