Swift solution - DFS, BFS


  • 0
    class Solution {
        func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
            if p == nil && q == nil {
                return true
            }
            if p == nil || q == nil {
                return false
            }
    
            if p?.val == q?.val {
                return isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right)
            }
    
            return false
        }
        
        func isSameTree_BFS(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
            var pStack = [TreeNode]()
            var qStack = [TreeNode]()
            
            if let p = p {
                pStack.append(p)
            }
            if let q = q {
                qStack.append(q)
            }
            while !pStack.isEmpty && !qStack.isEmpty {
                let pNode = pStack.removeLast()
                let qNode = qStack.removeLast()
                if pNode.val != qNode.val {
                    return false
                }
                
                if let pRightNode = pNode.right {
                    pStack.append(pRightNode)
                }
                if let qRightNode = qNode.right {
                    qStack.append(qRightNode)
                }
                if pStack.count != qStack.count {
                    return false
                }
                
                if let pLeftNode = pNode.left {
                    pStack.append(pLeftNode)
                }
                if let qLeftNode = qNode.left {
                    qStack.append(qLeftNode)
                }
                if pStack.count != qStack.count {
                    return false
                }
            }
            
            return pStack.count == qStack.count
        }
    }
    

Log in to reply
 

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