Binary Search Tree,二叉搜索树,节点的值没有重复,左子树所有值<根节点<右子树所有值,左子树和右子树也是BST;中序遍历BST得到一个递增数列。
平衡二叉树,左子树和右子树也是平衡二叉树,且左子树和右子树的高度差不超过1。
这题反过来很简单,直接中序遍历即可。
先用一个辅助数组做,先找到中间的数作为根节点(数组长度为奇数则是正中间,偶数则为靠前的那个中点),然后把左右两个子数组分别递归调用,成为左子树和右子树。注意子树为空的判断条件。
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null){
return null;
}
List<Integer> num = new ArrayList<>();
while(head != null){
num.add(head.val);
head = head.next;
}
return sortedListToBST(num, 0, num.size() - 1);
}
private TreeNode sortedListToBST(List<Integer> num, int left, int right){
if(left > right){
return null;
}
int mid = (left + right) / 2;
TreeNode root = new TreeNode(num.get(mid));
root.left = sortedListToBST(num, left, mid - 1);
root.right = sortedListToBST(num, mid + 1, right);
return root;
}
}
改进的方法是直接在原链表上操作,用快慢指针找到中点,因为是递归调用的,所以在一开始要把边界条件写好,快慢指针在链表只有两个节点时也不会报错,这时候一步都不会走,第一个节点就是中点;所以把原链表是空和只有一个节点的情况特殊处理一下。然后要用一个prev保存slow前一个节点,因为在找到中点,要递归地调用左右两个子链表时,右边的只需要传入slow.next就行了,而左边的传入head,但是要把prev.next置成Null,也就是把左链表要分离出来。
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null){
return null;
}
if(head.next == null){
return new TreeNode(head.val);
}
ListNode prev = null;
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
TreeNode root = new TreeNode(slow.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(slow.next);
return root;
}
}