236_Lowest Common Ancestor of a Binary Tree
236. Lowest Common Ancestor of a Binary Tree
Level: medium
Tag: tree
Question
Example 1
Idea
我们仍然可以用递归来解决,递归寻找两个带查询LCA的节点p和q,当找到后,返回给它们的父亲。如果某个节点的左右子树分别包括这两个节点,那么这个节点必然是所求的解,返回该节点。否则,返回左或者右子树(哪个包含p或者q的就返回哪个)。
Solution: recursive
Time:
Space:
Follow up: what if there is parent pointer?
Idea:
move p and q upward, record the parent nodes they visited in a set.
If one node is already visited, then this node is LCA.
Solution:
Time: , where is the hight of the tree
Space:
Last updated