add new solutions
This commit is contained in:
parent
d798d5e8c9
commit
886b5e0a8e
34 changed files with 1164 additions and 0 deletions
31
solutions/2/q236/solution.go
Normal file
31
solutions/2/q236/solution.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package q236
|
||||
|
||||
type TreeNode struct {
|
||||
Val int
|
||||
Left *TreeNode
|
||||
Right *TreeNode
|
||||
}
|
||||
|
||||
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||
if root == nil {
|
||||
return nil
|
||||
}
|
||||
if root == p || root == q {
|
||||
return root
|
||||
}
|
||||
|
||||
l := lowestCommonAncestor(root.Left, p, q)
|
||||
r := lowestCommonAncestor(root.Right, p, q)
|
||||
|
||||
switch {
|
||||
case l == nil && r == nil:
|
||||
return nil
|
||||
case l != nil && r != nil:
|
||||
return root
|
||||
case l != nil:
|
||||
return l
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
var _ = lowestCommonAncestor
|
||||
Loading…
Add table
Add a link
Reference in a new issue