Find Largest Value in Each Tree Row

LeetCode题目来源

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]
这道题我的办法是用DFS然后记录每个高度的值存在vector中,然后再分别排序

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
int cur_depth;
vector<int>dep_que[1000];

void dfs(TreeNode*root,int depth){
    if(root == NULL) return;
    else {
        if(cur_depth <= depth) cur_depth = depth;
        dep_que[depth].push_back(root->val);
    }
    dfs(root->left, depth+1);
    dfs(root->right, depth+1);
}

class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        vector<int>largest;
        if(root == NULL) return largest;
        for(int i = 0; i <= 1000; i++){
            dep_que[i].clear();
        }
        cur_depth = 0;
        dfs(root,0);
        for(int i = 0; i <= cur_depth; i++){
            sort(dep_que[i].begin(),dep_que[i].end());
            int max_index = dep_que[i].size()-1;
            largest.push_back(dep_que[i][max_index]);
        }

        return largest;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值