101. Symmetric Tree

83 阅读1分钟

题目描述

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example,
this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Follow up: Solve it both recursively and iteratively.

解题思路

这个题与100题类似, 只不过是我们递归比较的 l.left == r.right 和 l.right == r.left.
时间复杂度: O(n)

示例代码

func isSymmetric(_ root: TreeNode?) -> Bool {

    guard let root = root else { return true }

    return isSame(root.left, root.right) && isSame(root.right, root.left)
}


func isSame(_ left: TreeNode?, _ right: TreeNode?) -> Bool {

    if left == nil && right == nil {
        return true
    }
    guard let l = left,
    let r = right,
    l.val == r.val else { return false }
    return isSame(l.left, r.right) && isSame(l.right, r.left)
}