100. 相同的树

image.png

解题思路
相等的前提就是两个树左节点和左节点相等 ,右节点也一样的
迭代使用的是广度搜索 也就是层搜索 使用的数据结构是队列,

  1. package main
  2. import "fmt"
  3. type TreeNode struct {
  4. Val int
  5. Left *TreeNode
  6. Right *TreeNode
  7. }
  8. func isSameTree(p *TreeNode, q *TreeNode) bool {
  9. if p==nil&&q==nil{
  10. return true
  11. }
  12. if p!=nil&&q==nil||p==nil&&q!=nil||p.Val!=q.Val{
  13. return false
  14. }
  15. return isSameTree(p.Left,q.Left)&&isSameTree(p.Right,q.Right)
  16. }
  17. func isSameTree1(p *TreeNode, q *TreeNode) bool {
  18. if p==nil&&q==nil{
  19. return true
  20. }
  21. if p!=nil&&q==nil||p==nil&&q!=nil||p.Val!=q.Val{
  22. return false
  23. }
  24. queue :=make([]*TreeNode,0)
  25. queue = append(queue,p)
  26. queue = append(queue,q)
  27. for len(queue)>0{
  28. pNode :=queue[0]
  29. qNode :=queue[1]
  30. if pNode.Val!=qNode.Val{
  31. return false
  32. }
  33. if pNode.Left!=nil&&qNode.Left!=nil {
  34. queue = append(queue,pNode.Left)
  35. queue = append(queue,qNode.Left)
  36. } else if pNode.Left==nil&&qNode.Left!=nil {
  37. return false
  38. }else if pNode.Left!=nil&&qNode.Left==nil {
  39. return false
  40. }
  41. if pNode.Right!=nil&&qNode.Right!=nil {
  42. queue = append(queue,pNode.Right)
  43. queue = append(queue,qNode.Right)
  44. }else if pNode.Right==nil&&qNode.Right!=nil {
  45. return false
  46. }else if pNode.Right!=nil&&qNode.Right==nil {
  47. return false
  48. }
  49. queue =queue[2:]
  50. }
  51. return true
  52. }
  53. func main() {
  54. t11 := &TreeNode{Val: 1}
  55. t12 := &TreeNode{Val: 2}
  56. t11.Left = t12
  57. t13 := &TreeNode{Val: 1}
  58. t11.Right = t13
  59. t21 := &TreeNode{Val: 1}
  60. t22 := &TreeNode{Val: 1}
  61. t21.Left = t22
  62. t23 := &TreeNode{Val: 2}
  63. t21.Right = t23
  64. fmt.Println(isSameTree1(t11,t21))
  65. }