450. Delete Node in a BST
给一个bst根结点和一个整数val,删除bst中等于val的结点。
从根结点开始遍历,
- 如果val等于当前结点就将当前结点右子树中最左边的元素和当前结点替换,然后再递归进入右子树删除最左边的结点
- 如果val小于当前结点,递归进入左子树继续
- 如果val大于当前结点,递归进入右子树继续
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return null;
if (root.val > key) {
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
root.right = deleteNode(root.right, key);
} else {
if (root.left == null && root.right == null)
return null;
else if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
else {
int min = findMin(root.right);
// System.out.println(min);
root.val = min;
root.right = deleteNode(root.right, min);
}
}
return root;
}
public int findMin(TreeNode root) {
while (root.left != null) {
root = root.left;
}
return root.val;
}
501. Find Mode in Binary Search Tree
给一个含重复值的bst,返回出现频率最高的所有结点值组成的数组。
中序遍历,是一个有序数组,所以只要记录当前最大重复次数和该重复结点的值即可,遇到新的值就将重复次数改为1并继续累加。
一个关键点在于,当前结点重复次数大于最大重复次数时清空返回数组,然后再加入该值,可以保证数组中的值重复次数都是一样的(且都是最大的)
public int[] findMode(TreeNode root) {
helper(root);
int[] r = new int[res.size()];
for (int i = 0; i < r.length; i++) {
r[i] = res.get(i);
}
return r;
}
int len = 0;
int max = 0;
Integer last = null;
List<Integer> res = new ArrayList<>();
public void helper(TreeNode root) {
if (root != null) {
helper(root.left);
if (last != null) {
if (last == root.val) {
len++;
} else {
len = 1;
last = root.val;
}
} else {
last = root.val;
len++;
}
if (len > max) {
max = len;
res.clear();
}
if (len == max)
res.add(root.val);
helper(root.right);
}
}