标签:
Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
很简单的二分法,只要给出Array的开始和结束下标作为参数传入即可。
1 public TreeNode sortedArrayToBST(int[] num) { 2 return constructBST(num,0,num.length-1); 3 } 4 public TreeNode constructBST(int[] num, int start, int end) { 5 if(start>end) 6 return null; 7 if(start==end) 8 return new TreeNode(num[start]); 9 int mid = (start+end)/2; 10 TreeNode root = new TreeNode(num[mid]); 11 root.left = constructBST(num, start, mid-1); 12 root.right = constructBST(num, mid+1, end); 13 return root; 14 }
Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
对于链表来说,情况稍微复杂一些,最简单的思路是可以遍历一遍链表存到array中然后构建。这里采用直接构建的方法,就是用快慢指针找到链表中点,左半部分链表终点指向null,递归构建成左子树。右半部分递归构建成右子树即可。如果不想破坏原有链表那么可以采用先存到array中再构建的方法。
1 public TreeNode sortedListToBST(ListNode head) { 2 if(head==null) 3 return null; 4 if(head.next == null) 5 return new TreeNode(head.val); 6 ListNode fast = head.next; 7 ListNode slow = head; 8 while(fast!=null && fast.next!=null && fast.next.next!=null) { 9 fast = fast.next.next; 10 slow = slow.next; 11 } 12 ListNode root = slow.next; 13 slow.next = null; 14 TreeNode tRoot = new TreeNode(root.val); 15 tRoot.left = sortedListToBST(head); 16 tRoot.right = sortedListToBST(root.next); 17 return tRoot; 18 }
标签:
原文地址:http://www.cnblogs.com/splash/p/4423845.html