Topic source: 236. The nearest common ancestor of a binary tree
Topic: Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.
The definition of the nearest common ancestor in Baidu Encyclopedia is: "For two nodes p and q of a rooted tree T, the nearest common ancestor is represented as a node x, which satisfies that x is the ancestor of p, q and the depth of x is as large as possible (a A node can also be its own ancestor)."
Idea: Recursion
- If the root node is empty, or if the root node is equal to p or q, then the root node is its nearest common ancestor.
- If the root node is not empty, recursively call the left and right subtrees of the root node
- If the left subtree is empty, indicating that p and q are not in the left subtree, return the right subtree.
- If the right subtree is empty, indicating that p and q are not in the right subtree, return the left subtree.
- If the left and right subtrees are not empty, it means that the nearest common node is the root node, and the root node is returned.
Explanation: In fact, it is to use the idea of recursion to search for p and q left and right, and return the node that first encounters the p and q nodes, and then judge whether p and q are in the same subtree, and if so, return the corresponding subtree, If not, the common ancestor must be the root node, which is always recursively judged.
python code:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root or (root==p or root==q):
return root
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
if not left:
return right
if not right:
return left
return root
Reference source: [leetcode] The sword refers to Offer 68 - II. The nearest common ancestor of a binary tree (python3 version) The
nearest common ancestor of a binary tree (Python version)