1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package main
import "fmt"
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 }
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 }
func main() { root := &TreeNode{Val: 3} root.Left = &TreeNode{Val: 5} root.Right = &TreeNode{Val: 1} root.Left.Left = &TreeNode{Val: 6} root.Left.Right = &TreeNode{Val: 2} root.Right.Left = &TreeNode{Val: 0} root.Right.Right = &TreeNode{Val: 8} root.Left.Right.Left = &TreeNode{Val: 7} root.Left.Right.Right = &TreeNode{Val: 4}
p := root.Left q := root.Left.Right.Right
result := lowestCommonAncestor(root, p, q)
fmt.Printf("节点 %d 和节点 %d 的最近公共祖先是节点 %d\n", p.Val, q.Val, result.Val) }
|