Featured image of post 101. 对称二叉树

101. 对称二叉树

题目描述

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:

  • 输入:root = [1,2,2,3,4,4,3]
  • 输出:true

示例 2:

  • 输入:root = [1,2,2,null,3,null,3]
  • 输出:false

解法一:递归

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func isSymmetric(root *TreeNode) bool {
    return check(root, root)
}

func check(p, q *TreeNode) bool {
    if p == nil && q == nil {
        return true
    }

    if p == nil || q == nil {
        return false
    }

    return p.Val == q.Val && check(p.Left, q.Right) && check(p.Right, q.Left)
}
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计