美文网首页
LeetCode - Find Largest Value in

LeetCode - Find Largest Value in

作者: Andy1944 | 来源:发表于2019-07-22 17:10 被阅读0次

    Find Largest Value in Each Tree Row - LeetCode

    Solution

    class Solution {
        func largestValues(_ root: TreeNode?) -> [Int] {
            var dict = [Int: [Int]]()
            traversing(root, 0, &dict)
            var result = [Int]()
            for key in dict.keys.sorted() {
                result.append(dict[key]!.max()!)
            }
            return result
        }
        
        func traversing(_ root: TreeNode?, _ deep: Int, _ dict: inout [Int: [Int]]) {
            guard let root = root else {
                return
            }
            if let array = dict[deep] {
                dict[deep] = array + [root.val]
            } else {
                dict[deep] = [root.val]
            }
            traversing(root.left, deep + 1, &dict)
            traversing(root.right, deep + 1, &dict)
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode - Find Largest Value in

          本文链接:https://www.haomeiwen.com/subject/lsgwlctx.html