/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int height(struct TreeNode* node) {
if (node == NULL) return 0;
int l = height(node->left);
int r = height(node->right);
return (l > r ? l + 1 : r + 1);
}
int min(struct TreeNode* node) {
int res = node->val;
if (node->left) {
int l = min(node->left);
res = res > l ? l : res;
}
if (node->right) {
int r = min(node->right);
res = res > r ? r : res;
}
return res;
}
void traverse(struct TreeNode* node, int layer, int* res) {
if (node == NULL) return;
if (res[layer] < node->val) {
res[layer] = node->val;
}
traverse(node->left, layer + 1, res);
traverse(node->right, layer + 1, res);
return;
}
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* largestValues(struct TreeNode* root, int* returnSize) {
*returnSize = height(root);
int* res = (int*) malloc((*returnSize) * sizeof(int));
if (0 == *returnSize) return res;
int m = min(root);
for (int i = 0; i < *returnSize; i++) {
res[i] = m;
}
traverse(root, 0, res);
return res;
}
515 Find Largest Value in Each Tree Row
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 代码有点渣,效率不够高,简单的层次优先遍历,注意各种情况。。。。比如[],[-12,1,1],[1,-12,0]b...
- 寻找二叉树每层的最大值,递归先序遍历的方法实现,利用一个vector保存每层的最大值。
- You need to find the largest value in each row of a binar...
- You need to find the largest value in each row of a binar...