236. Lowest Common Ancestor of a Binary Tree
Question
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes
p
andq
as the lowest node inT
that has bothp
andq
as descendants (where we allow a node to be a descendant of itself).”
Solution
DFS搜索,后序遍历。
当当前节点是p或者q,返回节点自身,代表已经找到节点。(如两个节点最终只访问了一个,说明那一个节点本身就是LCA。)
分别递归搜索左右子节点。
如果左子节点为空,则返回右子节点,反之亦然,保证找到的节点可以被返回。
如果左右子节点均不等于null,则当前节点是最低公共祖先(LCA),返回当前节点。
Code
1 | /** |
236. Lowest Common Ancestor of a Binary Tree
https://xuanhe95.github.io/2022/05/03/236-Lowest-Common-Ancestor-of-a-Binary-Tree/