Home > AI > Data Structure > Tree >

leetcode-100-Same Tree

Swift solution:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init() { self.val = 0; self.left = nil; self.right = nil; }
 *     public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
 *     public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
 *         self.val = val
 *         self.left = left
 *         self.right = right
 *     }
 * }
 */
class Solution {
    func midOrder(_ p: TreeNode?) -> [String] {
        guard let p = p else {
            return ["null"]
        }
        var re: [String] = [String(p.val)]
        var left: [String] = midOrder(p.left)
        var right: [String] = midOrder(p.right)
        re.append(contentsOf: left)
        re.append(contentsOf: right)
        return re
    }
    
    func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
        var p1 = midOrder(p)
        var p2 = midOrder(q)
        return p1 == p2
    }
}

Leave a Reply