标签:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题解完全抄自ref的说明,感谢!
“
题解:
先复习下什么是二叉搜索树(引自Wikipedia):
二叉查找树(Binary Search Tree),也称有序二叉树(ordered binary tree),排序二叉树(sorted binary tree),是指一棵空树或者具有下列性质的二叉树:
再复习下什么是平衡二叉树(引自GeekforGeek):
An empty tree is height-balanced. A non-empty binary tree T is balanced if:
1) Left subtree of T is balanced
2) Right subtree of T is balanced
3) The difference between heights of left subtree and right subtree is not more than 1.
解决方法是选中点构造根节点,然后递归的构造左子树和右子树。
”
Tree 构建基本题 http://www.cnblogs.com/springfor/p/3879823.html
public class Solution { public TreeNode sortedArrayToBST(int[] nums) { if(nums==null || nums.length==0) return null; return helper(nums, 0, nums.length-1); } public TreeNode helper(int[] num, int low, int high){ if(low>high) return null; int mid = (low+high)/2; TreeNode root = new TreeNode(num[mid ]); root.left = helper(num,low, mid-1); root.right = helper(num, mid+1,high); return root; } }
Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4565051.html