forked from banjodayo39/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SameTree.swift
36 lines (33 loc) · 854 Bytes
/
SameTree.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Question Link: https://leetcode.com/problems/same-tree/
* Primary idea: recursion
* Time Complexity: O(n), Space Complexity: O(n)
*
* Copyright © 2016 YiGu. All rights reserved.
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class SameTree {
func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
guard let p = p else {
return q == nil
}
guard let q = q else {
return p == nil
}
if p.val != q.val {
return false
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}
}