題目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
題解:
先復習下什么是二叉搜索樹(引自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.
解決方法是選中點構造根節點,然后遞歸的構造左子樹和右子樹。
代碼如下:
1
public TreeNode buildTree(
int[] num,
int low,
int high){
2 if(low>high)
3 return null;
4
5 int mid = (low+high)/2;
6 TreeNode node = new TreeNode(num[mid]);
7 node.left = buildTree(num,low,mid-1);
8 node.right = buildTree(num,mid+1,high);
9 return node;
10 }
11 public TreeNode sortedArrayToBST( int[] num) {
12 return buildTree(num,0,num.length-1);
13 }
2 if(low>high)
3 return null;
4
5 int mid = (low+high)/2;
6 TreeNode node = new TreeNode(num[mid]);
7 node.left = buildTree(num,low,mid-1);
8 node.right = buildTree(num,mid+1,high);
9 return node;
10 }
11 public TreeNode sortedArrayToBST( int[] num) {
12 return buildTree(num,0,num.length-1);
13 }