leetcode:Convert Sorted Array to Binary Search Tree

来源:互联网 发布:新版淘宝联盟申请高佣 编辑:程序博客网 时间:2024/05/17 07:25

把已经排好序的数组,重塑成平衡二叉树,直接利用递归的思想做即可

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    static TreeNode root = null;    public TreeNode sortedArrayToBST(int[] num) {        // TreeNode root = null;        root = buildBST(num, 0, num.length - 1, root);        return root;    }    public static TreeNode buildBST(int[] num, int low, int height, TreeNode node){    if(low == height){    return new TreeNode(num[low]);    }    else if(low < height){    int mid = (low + height) / 2;    node = new TreeNode(num[mid]);    node.left = buildBST(num, low, mid - 1, node.left);    node.right = buildBST(num, mid + 1, height, node.right);    return node;    }    else return null;    }}


0 0
原创粉丝点击