Leetcode 515. Find Largest Value in Each Tree Row

You need to find the largest value in each row of a binary tree.

Example:

Input: 

          1
         / 
        3   2
       /      
      5   3   9 

Output: [1, 3, 9]



 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> largestValues(TreeNode* root) {
13         vector<int> ret;  // 存放结果值
14         if(root == nullptr)
15         {
16             return ret;    // 如果根节点指向空指针,则返回空。
17         }
18         dfs(root,0,ret);   //调用深度优先搜索函数,先序遍历搜索
19         return ret;
20     }
21 private:  
22     void dfs(const TreeNode* root, const int depth, vector<int> &res)// 深度优先搜索
23     {
24         if (root == nullptr)
25            return;                //如果是叶节点则返回
26         if (depth == res.size())  //如果此时的树深等于ret的长度,则将节点的值添加进去
27         {
28              res.push_back(root->val);
29         }
30         else//如果此时的深度不等于res的长度,说明这一层已经写进入过值,所以要进行比较
31         {
32             res[depth] = max(res[depth], root->val);
33         }
34         dfs(root->left, depth + 1, res);
35         dfs(root-> right, depth + 1, res);
36     }
37 };

 有几点需要注意的:

1. 深度优先搜索时的参数,depth是实参调用,每次函数里边的值是不改变上一层中的值,而根节点指针和结果res都是会变化的,res的长度是 引用传参。

2. 此时为先序遍历

原文地址:https://www.cnblogs.com/simplepaul/p/6713336.html