100. Same Tree

77 阅读1分钟

题目描述

Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:
Input:
1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true

Example 2:
Input:
1 1
/ \
2 2
[1,2], [1,null,2]
Output: false

解题思路

这个题目思路很简单, 我们首先判断给的2个节点是否都为nil, 如果是nil, 返回true (在递归遍历中也是终止条件), 然后, 我们判断2个节点是否都不为nil, 且val 相等, 否则就返回false, swift的 guard-let-else 语句可以很方便的实现这段代码, 如果2个节点的val相等, 我们就递归他们的 左节点和右节点同时相等
时间复杂度: O(n)

示例代码

func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
    if p == nil && q == nil {
        return true
    }
    guard let p = p,
        let q = q,
        p.val == q.val else {
            return false
    }
    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}