• lintcode: 把排序数组转换为高度最小的二叉搜索树


    题目:

    给一个排序数组(从小到大),将其转换为一棵高度最小的排序二叉树。

    样例

    给出数组 [1,2,3,4,5,6,7], 返回

         4
       /   
      2     6
     /     / 
    1   3  5   7
    
    挑战

    可能有多个答案,返回任意一个即可

    解题:

    可以看出,这里的数组是所求二叉树,中序遍历的结果,把这个结果还原成树即可。曾经天勤数据结果好像有这一题。

    Java程序:

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */ 
    public class Solution {
        /**
         * @param nums: an integer array
         * @return: a tree node
         */
        public TreeNode sortedArrayToBST(int[] nums) {  
            // write your code here
            if(nums==null)
                return null;
            return buildTree(nums,0,nums.length - 1);
        }
        public TreeNode buildTree(int[] nums,int start,int end){
            if(start>end)
                return null;
            int median = (start+end)/2;
            TreeNode node = new TreeNode(nums[median]);
            node.left = buildTree(nums,start,median-1);
            node.right = buildTree(nums,median+1,end);
        
            return node;
        }
    }
    View Code

    总耗时: 2855 ms

    Python程序:

    """
    Definition of TreeNode:
    class TreeNode:
        def __init__(self, val):
            self.val = val
            self.left, self.right = None, None
    """
    class Solution:
        """
        @param nums: a list of integer
        @return: a tree node
        """
        def sortedArrayToBST(self, nums):
            # write your code here
            if nums==None:
                return None
            return self.buildTree(nums,0,len(nums)-1)
        
        def buildTree(self,nums,start,end):
            if start>end:
                return None
            median = (start+end)//2
            node = TreeNode(nums[median])
            node.left = self.buildTree(nums,start,median-1)
            node.right = self.buildTree(nums,median+1,end)
            return node
    View Code

    总耗时: 869 ms

  • 相关阅读:
    FORTRAN学习记录
    Ubuntu查看和自动挂载硬盘
    正则表达式批量重命名
    [USACO 09FEB]Fair Shuttle
    [ZJOI 2012]灾难
    [BJOI 2010]次小生成树Tree
    Python开发 第一篇 python的前世今生
    关于pycharm字体大小的调整
    关于"人工智能Python""系统环境变量设置步骤
    [洛谷P1168]中位数
  • 原文地址:https://www.cnblogs.com/theskulls/p/4875784.html
Copyright © 2020-2023  润新知