image.png

迭代

  1. package main
  2. import "fmt"
  3. type TreeNode struct {
  4. Val int
  5. Left *TreeNode
  6. Right *TreeNode
  7. }
  8. func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
  9. for root!= nil{
  10. if root.Val>p.Val&&root.Val>q.Val {
  11. root = root.Left
  12. } else if root.Val<p.Val&&root.Val<q.Val {
  13. root = root.Right
  14. }else {
  15. return root
  16. }
  17. }
  18. return nil
  19. }
  20. func main() {
  21. six := &TreeNode{
  22. Val: 6,
  23. }
  24. two := &TreeNode{
  25. Val: 2,
  26. }
  27. six.Left = two
  28. eight := &TreeNode{
  29. Val: 8,
  30. }
  31. six.Right = eight
  32. zero := &TreeNode{
  33. Val: 0,
  34. }
  35. two.Left = zero
  36. four := &TreeNode{
  37. Val: 4,
  38. }
  39. two.Right = four
  40. three := &TreeNode{
  41. Val: 3,
  42. }
  43. four.Left = three
  44. five := &TreeNode{
  45. Val: 5,
  46. }
  47. four.Right = five
  48. seven := &TreeNode{
  49. Val: 7,
  50. }
  51. eight.Left = seven
  52. nine := &TreeNode{
  53. Val: 9,
  54. }
  55. eight.Right = nine
  56. fmt.Println(lowestCommonAncestor(six,two,eight).Val)
  57. fmt.Println(lowestCommonAncestor(six,two,four).Val)
  58. }

image.png

递归

  1. func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
  2. if root.Val > p.Val && root.Val > q.Val {
  3. root = lowestCommonAncestor(root.Left, p, q)
  4. }
  5. if root.Val < p.Val && root.Val < q.Val {
  6. root = lowestCommonAncestor(root.Right, p, q)
  7. }
  8. return root
  9. }

image.png