二叉树节点的最近邻公共祖先节点
介绍
求一个二叉树中两个节点的最近邻公共祖先节点(LCA
According to the definition of LCA on Wikipedia: “The lowest common
ancestor is defined between two nodes v and w as the lowest node in T
that has both v and w as descendants (where we allow a node to be a
descendant of itself).”
)。旨在掌握递归的运用,练习题目为LeetCode第235题与第236题。
235. BST的LCA
_______6______
/ \
__2___ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
BST的特点是结点的左子树上的所有结点的值都不大于它,右子树上所有结点的值都比它大。
因此对于要寻找LCA的两个结点p,q,根节点的值r有:
- 如果结点值p,q>r,则p,q都是r的右子树上的节点;
- 如果结点值p,q≤r,则p,q都是r的左子树上的节点;
- 如果结点值p≤r≤q,则r为p,q的LCA。
具体实现代码为:
<