您的位置:首页 > 产品设计 > UI/UE

LeetCode之Find Largest Value in Each Tree Row

2017-07-06 16:19 393 查看
本题的意思是给定一个二叉树,输出这棵树每层中最大的数。

我采用DFS的算法来解决此题。按照从左至右DFS的顺序遍历给定的二叉树,先将每层最左边的数当作当前每层的最大数依次加入到数组,然后在DFS的过程中,不断更新同层的最大数,当遍历完树时,更新完的数组即为所求。

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
void dfs(TreeNode* root, vector<int>& max, int d) {
if(root == NULL){
return;
}

if((d == 0 && max.empty()) || d == max.size()) {
max.push_back(root -> val);
} else {
max[d] = max[d] > root -> val ? max[d] : root -> val;
}

dfs(root -> left, max, d + 1);
dfs(root -> right, max, d + 1);
}

public:
vector<int> largestValues(TreeNode* root) {
vector<int> max;

dfs(root, max, 0);

return max;
}
};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: