-
Notifications
You must be signed in to change notification settings - Fork 21
/
SameTree.swift
44 lines (35 loc) 路 1.05 KB
/
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
37
38
39
40
41
42
43
44
//
// SameTree.swift
// LeetCode
//
// Created by 榛庤档澶儙 on 27/11/2017.
// Copyright 漏 2017 lizhaotailang. All rights reserved.
//
// Given two binary trees, write a function to check if they are equal or not.
//
// Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
//
// Accepted. See [SameTree](./LeetCodeTests/SameTreeTests.swift) for test cases.
//
import Foundation
class SameTree {
func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
if p == nil && q == nil {
return true
}
if p == nil || q == nil {
return false
}
return p?.val == q?.val && isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right)
}
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
}
}
}