给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
提示:
- 树中节点数目在范围 [1, 1000] 内
- -100 <= Node.val <= 100
解题:
func isSymmetric(root *TreeNode) bool {
if root == nil {
return true
}
left, right := root.Left, root.Right
var dfs func(left, right *TreeNode) bool
dfs = func(left, right *TreeNode) bool {
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
if left.Val != right.Val {
return false
}
return dfs(left.Left, right.Right) && dfs(left.Right, right.Left)
}
return dfs(left, right)
}
官方解答:
1.递归
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)
}
2.迭代
func isSymmetric(root *TreeNode) bool {
u, v := root, root
var q []*TreeNode
q = append(q, u)
q = append(q, v)
for len(q) > 0 {
u, v = q[0], q[1]
q = q[2:]
if u == nil && v == nil {
continue
}
if u == nil || v == nil {
return false
}
if u.Val != v.Val {
return false
}
q = append(q, u.Left, v.Right)
q = append(q, u.Right, v.Left)
}
return true
}