Not a BST. Have to iterate through the whole tree.
null, orp/qor not.- Recursive results:
left,right.
For left(or right), if left != null, 2 possibilities:
pandqare both in left subtree,porqis LCA;- both in substree, a parent node of both is LCA;
No matter what it is, left is not null; same for right;
=>
left,rightare both notnull: one in left subtree, one in right subtree.rootis LCA;- Both in
leftsubtree:lowestCommonAncestorwould recursively find the LCA in left subtree, then return; - same as 2, in right subtree.
1 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { |