Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
递归。找到数组的中点作为root,左边递归构造左子树,右边递归构造右子树。
条件判断有点写重复了。。。
1 public TreeNode sortedArrayToBST(int[] num) { 2 if (num.length == 0) return null; 3 else if (num.length == 1) return new TreeNode(num[0]); 4 else { 5 TreeNode root = sortedArrayToBST(num, 0, num.length-1); 6 return root; 7 } 8 } 9 public TreeNode sortedArrayToBST(int[] num, int start, int end) { 10 if (end - start < 0) return null; 11 else if (end - start == 0) { 12 return new TreeNode(num[end]); 13 } 14 else { 15 int m = (start + end)/2; 16 TreeNode root = new TreeNode (num[m]); 17 TreeNode left = sortedArrayToBST(num, start, m-1); 18 TreeNode right = sortedArrayToBST(num, m+1, end); 19 root.left = left; 20 root.right = right; 21 return root; 22 } 23 }
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
我一想,直接把sorted list 变成sorted array不就行了吗。。。但是它的确行。。
后来网上看到一种方法学习了一下。不用每次遍历然后找到list的中点。
思路就是从list头开始访问,按照list的顺序构造BST。之前的方法是从up-to-bottom,这里是bottom-to-up。
先构造左子树,然后根节点,然后右子树。
注意:这里为啥要构造一个wrapper类。如果直接使用ListNode类作为参数的话,sortedListToBST2(Wrapper head, int start, int end) 结束之后 head还是在操作之前的head,不会移到中点的位置。(感觉就像是一个值传递)。而如果用了wrapper的话,返回时head就在中点的位置(感觉就像是引用传递)。具体为啥还没搞懂。。。。
1 public static class Wrapper { 2 ListNode node; 3 } 4 5 public static TreeNode sortedListToBST2(ListNode head) { 6 ListNode t = head; 7 int n = 0; 8 while (t != null) { 9 n++; 10 t = t.next; 11 } 12 Wrapper w = new Wrapper(); 13 w.node = head; 14 TreeNode root = sortedListToBST2(w, 0, n-1); 15 return root; 16 } 17 18 public static TreeNode sortedListToBST2(Wrapper head, int start, int end) { 19 if (start > end) return null; 20 else { 21 int m = (start+end)/2; 22 TreeNode left = sortedListToBST2(head, start, m-1); 23 TreeNode root = new TreeNode(head.node.val); 24 root.left = left; 25 head.node = head.node.next; 26 TreeNode right = sortedListToBST2(head, m+1, end); 27 root.right = right; 28 return root; 29 } 30 }