[树先序遍历]LeetCode515. Find Largest Value in Each Tree Row

[树先序遍历]LeetCode515. Find Largest Value in Each Tree Row_第1张图片

寻找二叉树每层的最大值,递归先序遍历的方法实现,利用一个vector保存每层的最大值。

/**
 * 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 {
    vector vecRecordMax;
public:
    void findMAX(TreeNode* now, int level) {
        if(now == NULL)
            return;
        if(vecRecordMax.size() <= level) { //no record
            vecRecordMax.push_back(now->val);
        } else {
            if(now->val > vecRecordMax[level])
                vecRecordMax[level] = now->val;
        }
        
        findMAX(now->left, level + 1);
        findMAX(now->right, level + 1);
    }
    vector largestValues(TreeNode* root) {
        findMAX(root, 0);
        return vecRecordMax;
    }
};

你可能感兴趣的:([树先序遍历]LeetCode515. Find Largest Value in Each Tree Row)