KK's blog

每天积累多一些

0%

LeetCode 236 Lowest Common Ancestor of a Binary Tree

LeetCode



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 and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1:



Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.


Example 2:



Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.


Example 3:

Input: root = [1,2], p = 1, q = 2
Output: 1


Constraints:

The number of nodes in the tree is in the range [2, 10<sup>5</sup>]. -10<sup>9</sup> <= Node.val <= 10<sup>9</sup>
All Node.val are unique. p != q
* p and q will exist in the tree.

题目大意:

二叉树中求给定的两节点的最低共同父亲节点

解题思路:

DFS

解题步骤:

N/A

注意事项:

  1. pq一定存在,所以有**三种情况: 1) p或q是root,另一是其子孙。 2) p,q分列root两边。 3) p,q在root的一边

Python代码:

1
2
3
4
5
6
7
8
9
10
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root:
return None
if root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left if left else right

算法分析:

时间复杂度为O(n),空间复杂度O(1)


算法II解题思路:

BFS遍历树(可以找到就停止),然后记录子节点到父节点的映射,将所有父节点放到set中,同样查找另一个节点的父节点们,找到第一个在set中的节点。

Free mock interview