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

[leetcode 515]Find Largest Value in Each Tree Row

2017-03-03 13:37 357 查看

问题描述

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]

代码

深搜而已。

int cal_depth(TreeNode* root) {
if (root == NULL)
return 0;
return max(cal_depth(root->left),cal_depth(root->right))+1;
}
void cal(TreeNode* root,vector<int>& result,int depth) {
if (root == NULL)
return;
if (result[depth] < root->val)
result[depth] = root->val;
cal(root->left,result,depth+1);
cal(root->right,result,depth+1);
}
vector<int> largestValues(TreeNode* root) {
int depth = cal_depth(root);
vector<int> result(depth,1<<31);
cal(root,result,0);
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode