Skip to content

Commit

Permalink
[Tree] add Solution to SameTree
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Mar 31, 2016
0 parents commit 89ab679
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions Tree/SameTree.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Question Link: https://leetcode.com/problems/same-tree
* Primary solution: recursion
* Time Complexity: O(n), Space Complexity: O(1)
*
* 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 {
if (p == nil && q == nil) {
return true
}
if (p == nil || q == nil || p?.val != q?.val) {
return false
}

return isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right)
}
}

0 comments on commit 89ab679

Please sign in to comment.