public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { Infoinfo=newInfo(null, 0); helper(root, p, q, info); return info.result; }
// result == 0 neither is found // result == 1 first node is found // result == 2 second node is found privatevoidhelper(TreeNode node, TreeNode p, TreeNode q, Info info) { intcurrentFoundNum= info.foundNum; if (node == p || node == q) { info.foundNum += 1; if (info.foundNum == 2) return; } if (node.left != null) { helper(node.left, p, q, info); }
// Find the lowest? if (info.result != null) return; elseif (info.foundNum - currentFoundNum == 2) { // If this node is the lowest? info.result = node; return; } if (node.right != null) { helper(node.right, p, q, info); } if (info.result == null && (info.foundNum - currentFoundNum) == 2) { info.result = node; }