题目
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.
Note:
- All of the nodes’ values will be unique.
- p and q are different and both values will exist in the binary tree.
解法1:DFS
利用mid,left,right三个boolean变量代表当前节点为p,q中的一个,或者左子树或右子树中存在p和q中的node
算法流程
- 从根节点开始遍历整颗树
- 如果当前节点为p或q中的一个,那么将mid的值设为True然后继续搜索向下搜索当前节点的左子树和右子树
- left和right的值与mid一样,当recursion到某个level的时候,这个节点的mid值就是上层recursion结果的left和right,所以left和right即为recurse_tree的返回值
- 若mid,left,right这三个值的和大于等于2,证明当前节点即为我们要寻找的答案
class Solution(object):
def __init__(self):
self.ans = None
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
def recurse_tree(current_node):
if not current_node:
return False
left = recurse_tree(current_node.left)
right = recurse_tree(current_node.right)
mid = (current_node==p or current_node==q)
if mid+left+right >= 2:
self.ans = current_node
return mid or left or right
时间复杂度:O(N), N为节点的个数,因为最差的情况我们可能需要访问整颗树的所有节点
空间复杂度:O(N), N同样为节点的个数,因为这棵树的最大深度可以是N
二刷DFS1
二刷的时候看到一种非常intuitive但是比较慢的解法
class