515. Find Largest Value in Each Tree Row

来源:互联网 发布:Vb string 编辑:程序博客网 时间:2024/05/27 03:25

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]

不明白这样的题目还是medium,所以直接提交代码了。。。
主要是利用了一个队列,然后每次找出一层的一个最大值,存在数组之中即可,依次知道队列中没有元素。

vector<int> largestValues(TreeNode* root) {        vector<int> res;        if (root == NULL)return res;        queue<TreeNode *> data;        data.push(root);        while(!data.empty()){            int size = data.size();            int temp = INT_MIN;            for (int i = 0; i < size; i++){                TreeNode *p = data.front();                data.pop();                temp = max(temp, p->val);                if (p->left)data.push(p->left);                if (p->right)data.push(p->right);            }            res.push_back(temp);        }        return res;    }
原创粉丝点击