Jianzhi offer interview questions 68-II. The nearest common ancestor of a binary tree (recursive)

Title description

Given a binary tree, find the nearest common ancestor of the two specified nodes in the tree.
The definition of the most recent public ancestor in Baidu Encyclopedia is: "For the two nodes p and q of the rooted tree T, the most recent public ancestor is represented as a node x, satisfying that x is the ancestor of p and q and the depth of x is as large as possible (A node can also be its own ancestor.)
For example, given the following binary tree: root = [3,5,1,6,2,0,8, null, null, 7,4]

Insert picture description here

Ideas

See link for details

Code

class Solution:
	def lowestCommonAncestor(self,root,p,q):
		if not root or root.val ==p or root.val == 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
Published 227 original articles · praised 633 · 30,000+ views

Guess you like

Origin blog.csdn.net/weixin_37763870/article/details/105463107