題目:
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 }