题解 | #将升序数组转化为平衡二叉搜索树#

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

http://www.nowcoder.com/practice/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 (0 == num.length) {
            return null;
        }
        if (1 == num.length) {
            return new TreeNode(num[0]);
        }

        return process(num, 0, num.length - 1);
    }

    public TreeNode process(int[] num, int start, int end) {
        if (start > end) {
            return null;
        }
        if (start == end) {
            return new TreeNode(num[start]);
        }
        int mid = start + ((end - start) >> 1);
        TreeNode node = new TreeNode(num[mid]);
        TreeNode leftNode = process(num, start, mid - 1);
        TreeNode rightNode = process(num, mid + 1, end);
        node.left = leftNode;
        node.right = rightNode;
        return node;
    }
}
全部评论

相关推荐

挣K存W养DOG:他真的很中意你,为什么不回他
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务