Swift, C++ using dfs

  • 0

    Let the index in the result vector is the number of level in the tree,
    while dfs the tree, get max(result[level], root.val) so when finished,
    we got all the max number in the vector;

    class Solution {
        var result = [Int]()
        func largestValues(_ root: TreeNode?) -> [Int] {
            dfs(root, 0)
            return result
        func dfs(_ root: TreeNode?, _ lv: Int){
            if let root = root { // unwarp root pointer;
                if lv < result.count {
                    result[lv] = max(result[lv], root.val)
                dfs(root.left, lv+1)


    class Solution {
        vector<int> largestValues(TreeNode* root) {
    // B : we could get level num while dfs, so compare it with result.size() to update the max;
            vector<int> result; 
            dfs(root, 0, result); 
            return result; 
        void dfs(TreeNode *root, int lv, vector<int> &result){
            if(!root) return; 
            if(lv < result.size()){
                result[lv] = max(result[lv], root->val); 
            dfs(root->left, lv+1, result); 
            dfs(root->right, lv+1, result); 

Log in to reply

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