Swift solution - DFS


  • 0
    class Solution {
        func isSubtree(_ s: TreeNode?, _ t: TreeNode?) -> Bool {
            if s == nil || t == nil {
                return false
            }
            
            if s?.val == t?.val {
                if isSameTree(s, t) {
                    return true
                }
            }
            
            return isSubtree(s?.left, t) || isSubtree(s?.right, t)
        }
        
        func isSameTree(_ s: TreeNode?, _ t: TreeNode?) -> Bool {
            if s == nil || t == nil {
                return s == t
            }
            
            if s?.val != t?.val {
                return false
            }
            
            return isSameTree(s?.left, t?.left) && isSameTree(s?.right, t?.right)
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.