Skip to content

Commit

Permalink
[Tree] add Solution to PathSum, refactor code style
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Mar 31, 2016
1 parent cbc53ad commit fe91f0e
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 11 deletions.
30 changes: 30 additions & 0 deletions Tree/PathSum.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Question Link: https://leetcode.com/problems/path-sum/
* Primary idea: recursion
* Time Complexity: O(n), Space Complexity: O(1)
*
* 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 PathSum {
func hasPathSum(root: TreeNode?, _ sum: Int) -> Bool {
if root == nil {
return false
}
if sum == root!.val && root!.left == nil && root!.right == nil {
return true
}

return hasPathSum(root!.left, sum - root!.val) || hasPathSum(root!.right, sum - root!.val)
}
}
10 changes: 5 additions & 5 deletions Tree/SameTree.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* Question Link: https://leetcode.com/problems/same-tree
* Primary solution: recursion
* Question Link: https://leetcode.com/problems/same-tree/
* Primary idea: recursion
* Time Complexity: O(n), Space Complexity: O(1)
*
* Copyright © 2016 YiGu. All rights reserved.
Expand All @@ -20,13 +20,13 @@

class SameTree {
func isSameTree(p: TreeNode?, _ q: TreeNode?) -> Bool {
if (p == nil && q == nil) {
if p == nil && q == nil {
return true
}
if (p == nil || q == nil || p?.val != q?.val) {
if p == nil || q == nil || p!.val != q!.val {
return false
}

return isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right)
return isSameTree(p!.left, q!.left) && isSameTree(p!.right, q!.right)
}
}
12 changes: 6 additions & 6 deletions Tree/SymmetricTree.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* Question Link: https://leetcode.com/problems/symmetric-tree/
* Primary solution: recursion
* Primary idea: recursion
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for a binary tree node.
Expand All @@ -17,21 +17,21 @@
*
*/

class Solution {
class SymmetricTree {
func isSymmetric(root: TreeNode?) -> Bool {
if (root == nil) {
if root == nil {
return true
}
return helper(root!.left, root!.right)
}

func helper(p: TreeNode?, _ q:TreeNode?) -> Bool {
if (p == nil && q == nil) {
if p == nil && q == nil {
return true
}
if (p == nil || q == nil || p?.val != q?.val) {
if p == nil || q == nil || p!.val != q!.val {
return false
}
return helper(p?.left, q?.right) && helper(p?.right, q?.left)
return helper(p!.left, q!.right) && helper(p!.right, q!.left)
}
}

0 comments on commit fe91f0e

Please sign in to comment.