二叉查找树(BST):根节点大于等于左子树所有节点,小于等于右子树所有节点。
二叉查找树中序遍历有序。
中序遍历一棵二叉搜索树的结果是得到一个升序序列。
例题:
1.修剪二叉搜索树
class Solution {
public TreeNode trimBST(TreeNode root, int L, int R) {
return helper(root,L,R);
}
private TreeNode helper(TreeNode root, int L, int R){
if (root==null) return root;
if (root.val<L) return helper(root.right,L,R);
if (root.val>R) return helper(root.left,L,R);
root.left=helper(root.left,L,R);
root.right=helper(root.right,L,R);
return root;
}
}
- 有序链表转换二叉搜索树
class Solution {
private List<Integer> values;
public Solution() {
this.values = new ArrayList<Integer>();
}
private void mapListToValues(ListNode head) {
while (head != null) {
this.values.add(head.val);
head = head.next;
}
}
private TreeNode convertListToBST(int left, int right) {
// Invalid case
if (left > right) {
return null;
}
// Middle element forms the root.
int mid = (left + right) / 2;
TreeNode node = new TreeNode(this.values.get(mid));
// Base case for when there is only one element left in the array
if (left == right) {
return node;
}
// Recursively form BST on the two halves
node.left = convertListToBST(left, mid - 1);
node.right = convertListToBST(mid + 1, right);
return node;
}
public TreeNode sortedListToBST(ListNode head) {
// Form an array out of the given linked list and then
// use the array to form the BST.
this.mapListToValues(head);
// Convert the array to
return convertListToBST(0, this.values.size() - 1);
}
}