publicvoidgetMD(TreeNode root) { if (root == null) { return; }
// left getMD(root.left);
// root if (prev != null) {
// actually, no need to use abs, as this is a BST, // the value of the node behind should be larger than its former element // int gap = Math.abs(root.val - prev.val); // int gap = root.val - prev.val; // if (gap < minGap) { // minGap = gap;; // }
// Step 2: update the ans list if necessary if (tempCount == highestFrequence) { ans.add(cur.val); }elseif (tempCount > highestFrequence) { // note here, if higher frequence exists, then drop all the current cached res highestFrequence = tempCount; ans.clear(); ans.add(cur.val); }
// as a root node of any sub-tree, is my left branch and my right branck both // do not contain the target nodes, then I would definitely not be the LCA if(left == null && right == null) { returnnull; // similarly, if both my sub-tree contain the target, then because we // are backtracking, myself must be the LCA }elseif (left != null && right != null) { return root;
// if left does not contain target nodes, then the ans must be in the rightside }elseif (left == null && right != null) { return right; }else { // the same with the leftside return left; } } }