版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412923
思路
依然是找最近公共祖先,只不过BST换成了普通二叉树
code
代码语言:javascript复制type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
return helper(root, p, q)
}
func helper(root, p, q *TreeNode) *TreeNode {
if root == nil {
return nil
}
left := helper(root.Left, p, q)
right := helper(root.Right, p, q)
if root == p || root == q {
return root
}
if left != nil && right != nil {
return root
}
if left != nil && right == nil {
return left
}
if left == nil && right != nil {
return right
}
return nil
}