Java 递归分治法

将升序数组转化为平衡二叉搜索树

http://www.nowcoder.com/questionTerminal/7e5b00f94b254da599a9472fe5ab283d

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param num int整型一维数组 
     * @return TreeNode类
     */
    public TreeNode sortedArrayToBST (int[] num) {
        // write code here
        if(num == null){
            return null;
        }
        return helper(num, 0, num.length - 1);
    }

    private TreeNode helper(int[] num, int left, int right){
        if(left > right){
            return null;
        }
        int mid = left + (right - left + 1) / 2;
        TreeNode lNode = helper(num, left, mid - 1);
        TreeNode rNode = helper(num, mid + 1, right);
        TreeNode node = new TreeNode(num[mid]);
        if(lNode != null) node.left  = lNode;
        if(rNode != null) node.right = rNode;
        return node;
    }
}
全部评论
int mid = left + (right - left + 1) / 2; 这一步是为啥啊
点赞 回复 分享
发布于 2021-07-28 10:22

相关推荐

在下uptown:山东的哥们得好好回答 第一问题,专业技能太少了,现在写的大部分都是模型迭代过渡期的技术栈,说白了今天用明天可能就不用,多补一些看家的本事 第二个问题,项目偏学术学习体现不出工程能力,deepresearch核心在于模型自我反馈自我纠正,没体现出来,RAG本身在落地应用上就是个伪命题。 再有就是,有实习经历可以弥补学历不足,建议放到学历下面,别人筛简历可能第一眼觉得学校不过关,但第二眼有实习经历,就给你面试了,藏到后面可能就没有第二眼了
点赞 评论 收藏
分享
评论
3
5
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务