Skip to content

Commit

Permalink
公共祖先的特定判断方法
Browse files Browse the repository at this point in the history
  • Loading branch information
gdis5251 committed Aug 2, 2021
1 parent 1f8417b commit ddcd4ff
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions 精选/04.08.首个共同祖先/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

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

if root.Val == p.Val || root.Val == q.Val {
return root
}

lNode := lowestCommonAncestor(root.Left, p, q)
rNode := lowestCommonAncestor(root.Right, p, q)

if lNode != nil && rNode != nil {
return root
}

if lNode == nil {
return rNode
}

return lNode
}

0 comments on commit ddcd4ff

Please sign in to comment.