# Swift, C++ using dfs

• 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;
swift:

``````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)
}else{
result.append(root.val)
}
dfs(root.left, lv+1)
dfs(root.right,lv+1)
}
}

}
``````

c++:

``````class Solution {
public:
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);
}else{
result.push_back(root->val);
}
dfs(root->left, lv+1, result);
dfs(root->right, lv+1, result);
}
}
``````

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