Not a BST. Have to iterate through the whole tree.
null
, orp
/q
or not.- Recursive results:
left
,right
.
For left
(or right
), if left != null
, 2 possibilities:
p
andq
are both in left subtree,p
orq
is LCA;- both in substree, a parent node of both is LCA;
No matter what it is, left
is not null
; same for right;
=>
left
,right
are both notnull
: one in left subtree, one in right subtree.root
is LCA;- Both in
left
subtree:lowestCommonAncestor
would 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) { |