Leetcode: Convert Sorted Array to Binary Search Tree 理解分析

来源:互联网 发布:乐器软件模拟器 编辑:程序博客网 时间:2024/06/03 13:48

题目大意:给定一个升序的数组,将该数组转换成一个二叉搜索树,且是平衡的。

理解:1)将一个升序排列的数组转换成一个平衡二叉搜索树;

2)根节点单独处理,然后分别递归创建左右子树。注意:将引用传递给另一个方法,该引用是无法传回的。

实现:

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {        public TreeNode func(int[] s, int low, int high, TreeNode p) {        if(low > high) return null;                int mid = (low + high) >> 1;        p = new TreeNode(s[mid]);                p.left = func(s, low, mid - 1, p.left);        p.right = func(s, mid + 1, high, p.right);        return p;    }        public TreeNode sortedArrayToBST(int[] num) {        if(num == null || num.length == 0) return null;        int len = num.length;        int mid = len >> 1;        TreeNode root = new TreeNode(num[mid]);        if(len == 1) return root;        if(len == 2) {            root.left = new TreeNode(num[0]);            return root;        }        root.left = func(num, 0, mid - 1, root.left); // 创建左子树        root.right = func(num, mid + 1, len - 1, root.right); // 创建右子树        return root;    }}


0 0