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

    题目:

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

    链接: http://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

    题解:

    排序好的数组转换为BST, 找中点即可。

    Time Complexity - O(n), Space Complexity - O(n)。

    /**
     * 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) {
            if(nums == null || nums.length == 0)
                return null;
            return sortedArrayToBST(nums, 0, nums.length - 1);
        }
        
        private TreeNode sortedArrayToBST(int[] nums, int lo, int hi) {
            if(lo > hi)
                return null;
            int mid = lo + (hi - lo) / 2;
            TreeNode root = new TreeNode(nums[mid]);
            root.left = sortedArrayToBST(nums, lo, mid - 1);
            root.right = sortedArrayToBST(nums, mid +1, hi);
            return root;
        } 
    }

    二刷:

    一刷代码比较简洁,不像自己写的...

    主要我们就是利用一个辅助方法,使用二分法来自顶向下递归构建树。也可以使用自底向上,另外一题Convert Sorted List to BST就适合用自底向上方法。

    Java:

    Time Complexity - O(n), Space Complexity - O(n)。

    /**
     * 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) {
            if (nums == null || nums.length == 0) return null;
            return buildTree(nums, 0, nums.length - 1);
        }
        
        private TreeNode buildTree(int[] nums, int lo, int hi) {
            if (lo > hi) return null;
            int mid = lo + (hi - lo) / 2;
            TreeNode node = new TreeNode(nums[mid]);
            node.left = buildTree(nums, lo, mid - 1);
            node.right = buildTree(nums, mid + 1, hi);
            return node;
        }
    }

    测试:

  • 相关阅读:
    26 转义符 re模块 方法 random模块 collection模块的Counter方法
    25 正则表达式
    24 from 模块 import 名字
    24 from 模块 import 名字
    24 from 模块 import 名字
    23 析构方法 items系列 hash方法 eq方法
    21 isinstance issubclass 反射 _str_ _new_ _len_ _call_
    20 属性, 类方法, 静态方法. python2与python3的区别.
    python(1)
    python之字符串格式化
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4437315.html
Copyright © 2011-2022 走看看