面试题28. 对称的二叉树

image.png

  1. package main
  2. type TreeNode struct {
  3. Val int
  4. Left *TreeNode
  5. Right *TreeNode
  6. }
  7. func isSymmetric(root *TreeNode) bool {
  8. if root==nil {
  9. return true
  10. }
  11. return helper(root.Left,root.Right)
  12. }
  13. func helper(a ,b *TreeNode)bool{
  14. if a==nil&&b==nil {
  15. return true
  16. }
  17. if a==nil||b==nil {
  18. return false
  19. }
  20. if a.Val!=b.Val {
  21. return false
  22. }
  23. return helper(a.Left,b.Right)&&helper(a.Right,b.Left)
  24. }
  25. func main() {
  26. }

递归思路

image.png