Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
1 2 3 4 5 6 7 8 9 10 11 |
func isSymmetricTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool { if let p = p, let q = q { return p.val == q.val && isSymmetricTree(p.left, q.right) && isSymmetricTree(p.right, q.left) } else { return p == nil && q == nil } } func isSymmetric(_ root: TreeNode?) -> Bool { return isSymmetricTree(root?.left, root?.right) } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼