classSolution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { // if root.val == q.val or p.val then no need to traverse if (root == null || root.val == q.val || root.val == p.val) { return root; }
// if both q's and p's val are less than root.val then search the left side if (root.val > q.val && root.val > p.val) { return lowestCommonAncestor(root.left, p, q); }
// if both q's and p's val are larger than root.val then search the right side if (root.val < q.val && root.val < p.val) { return lowestCommonAncestor(root.right, p, q); }
// else it means that the two nodes are in both sides, no matter q is in left && // p in the right or the reversed situation, just return root return root;
classSolution { public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) { return root; } List<Integer> list = newLinkedList<>();
// if root is the node to delete if (root.val == key) {
// if right branch is null then return left if (root.left != null && root.right == null) { return root.left; }
// if left branch is null then return right if (root.left == null && root.right != null) { return root.right; }
// if no children just return null if (root.left == null && root.right == null) { returnnull; }
// else: it means that both child nodes exist // find the leftmost child of root's right branch TreeNodenode= root.right; while (node.left != null) { node = node.left; } node.left = root.left; return root.right;
}else { if (root.val > key) { // we maintain that deleteNode returns the new node after deletion root.left = deleteNode(root.left, key); }else { root.right = deleteNode(root.right, key); } } return root; } }