lowest_common_ancestor

  • 2022-12-14
  • 浏览 (526)

lowest_common_ancestor.go 源码

package main

//二叉树的最近公共祖先

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
	if root == nil || root == p || root == q {
		return root
	}

	left := lowestCommonAncestor(root.Left, p, q)
	right := lowestCommonAncestor(root.Right, p, q)
	if left != nil && right != nil {
		return root
	}
	if left != nil {
		return left
	}
	return right
}

你可能感兴趣的文章

bst_lowest_commona_ancestor

combinations

generate_parentheses

0  赞