A Swift Solution


  • 0
    T
        func isSameTree(p: TreeNode?, _ q: TreeNode?) -> Bool {
            if p == nil && q == nil {
                return true
            }else if p == nil || q == nil {
                return false
            }else if p?.val == q?.val {
                return isSameTree(p?.left, q?.left) == true  && isSameTree(p?.right, q?.right) == true
            }else {
                return false
            }
        }
    

  • 0

    Nice recursion solution.

    Here is my solution without recursion. It doesn't look as concise as recursion, but it works well.

    func isSameTree(p: TreeNode?, _ q: TreeNode?) -> Bool {
        if p == nil && q == nil { return true }
        var pStack = [p]
        var qStack = [q]
        while !pStack.isEmpty && pStack.first! != nil && !qStack.isEmpty && qStack.first! != nil {
            let pNode = pStack.last!, qNode = qStack.last!
            if pNode!.val != qNode!.val {
                return false
            }
            pStack.popLast()
            qStack.popLast()
            if pNode!.right != nil && qNode!.right != nil {
                pStack.append(pNode?.right)
                qStack.append(qNode?.right)
            }else if (pNode!.right == nil && qNode!.right != nil) || (pNode!.right != nil && qNode!.right == nil) {
                return false
            }
            if pNode!.left != nil && qNode!.left != nil {
                pStack.append(pNode?.left)
                qStack.append(qNode?.left)
            }else if (pNode!.left == nil && qNode!.left != nil) || (pNode!.left != nil && qNode!.left == nil) {
                return false
            }
        }
        return p == nil || q == nil ? false : true
    }
    

Log in to reply
 

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