Table of Contents
I. Key Takeaways
- Double Pointers in a Tree --> Often used to keep track of the last visited node during traversal.
- In-order Traverse in Binary Search Tree (BST) --> Produces a one-dimentional array where nodes are arranged in an ascending order.
II. Leetcode Exercises
(Easy) 530. Minimum Absolute Difference in BST
Methods: In-order traversal, double pointers
Notes:
- Use in-order traversal while keeping track of the previous node, enabling comparison between the current node and its adjacent node.
- Since we are looking for the sallest difference in a tree, when we initialise minDiff with
Integer.MAX_VALUE
private class Solution {
private int minDiff;
private TreeNode prev;
public int getMinimumDifference(TreeNode root) {
minDiff = Integer.MAX_VALUE;
prev = null;
traverse(root);
return minDiff;
}
public void traverse(TreeNode root) {
if (root == null) { return; }
// Left
traverse(root.left);
// Root
if (prev != null) {
minDiff = Math.min(minDiff, Math.abs(root.val - prev.val));
}
prev = root;
// Right
traverse(root.right);
}
}
(Easy) 501. Find Mode in Binary Search Tree
Methods: In-order traversal
Notes:
- Utilise in-order traversal to process nodes in ascending order.
- Track the maximum frequency and record multiple mode values sharing the same frequency. Clear the recorded mode values when a new maximum frequency is found.
private class Solution {
private ArrayList<Integer> res;
private TreeNode prev;
private int maxCount;
private int count;
public int[] findMode(TreeNode root) {
count = 0;
maxCount = 0;
prev = null;
res = new ArrayList<>();
traverse(root);
int[] modes = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
modes[i] = res.get(i);
}
return modes;
}
public void traverse(TreeNode root) {
if (root == null) { return; }
traverse(root.left);
if (prev == null || prev.val != root.val) {
count = 1;
} else {
count++;
}
if (count > maxCount) {
res.clear();
res.add(root.val);
maxCount = count;
} else if (maxCount == count) {
res.add(root.val);
}
prev = root;
traverse(root.right);
}
}
(Medium) 236. Lowest Common Ancestor of a Binary Tree
Methods: Post-order traversal, return values back in recursion.
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) { return null; }
if (root == p) { return p; }
if (root == q) { return q; }
TreeNode resLeft = lowestCommonAncestor(root.left, p, q);
TreeNode resRight = lowestCommonAncestor(root.right, p, q);
if (resLeft != null && resRight == null) {
return resLeft;
} else if (resLeft == null && resRight != null) {
return resRight;
} else if (resLeft != null && resRight != null) {
return root;
}
return null;
}
}