【Leetcode 235】Lowest Common Ancestor of a Binary Search Tree
难度: 简单(Easy)
题目
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 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).”
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
思路
当其中一个数是另一个的孩子时,那个父亲节点就是所求。否则,它们分别在最低共同祖先节点两侧。
代码
1 | # Definition for a binary tree node. |
评论系统未开启,无法评论!