码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 108. Convert Sorted Array to Binary Search Tree

时间:2016-05-04 19:05:12      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

把一个有序的数组转换为一颗平衡二叉搜索树。每次找到中间节点作为根节点,根节点左边部分转换为左子树,右边部分转换为右子树。代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode sortedArrayToBST(int[] nums) {
12         if(nums.length == 0) return null;
13         return changeToBST(nums, 0, nums.length-1);
14     }
15     
16     public TreeNode changeToBST(int[] nums, int left, int right){
17         int mid = (right - left)/2 + left;
18         TreeNode root = new TreeNode(nums[mid]);
19         if(left==mid) root.left = null;
20         else root.left = changeToBST(nums, left, mid-1);
21         if(right==mid) root.right = null;
22         else root.right = changeToBST(nums, mid+1, right);
23         return root;
24     }
25 }

 

LeetCode OJ 108. Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/liujinhong/p/5459151.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!