Find Largest Value in Each Tree Row(找出一棵树每一行的最大值)

来源:互联网 发布:批发源码 编辑:程序博客网 时间:2024/06/05 03:01

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]


找出树的每一行最大的值:

方法非常简单,用广度优先遍历

上述例子:首先将根节点存入一个队列q

对第一次循环,获得队列中节点个数c1(=1),每次从队列q中取出一个节点,比较该行最大值max1与该节点的值,用较大的值更新max1

同时将该节点的子节点存入队列中

这样当第一次循环,取完c1个节点时,队列中会个存在,前c1个节点所有子节点

如此第二次循环,获取队列中节点个数c2,正好等于第二层的节点数,同样的方法获得该层最大值

直至队列为空,代码如下:

public:    vector<int> largestValues(TreeNode* root) {        queue<TreeNode*> q;        vector<int> v;        if(root == NULL){            return v;        }        int c = 1;        q.push(root);        while(q.empty()==0){            int c = q.size();            int max = q.front()->val;            for(int i = 0; i < c; ++i){                TreeNode *t = q.front();                q.pop();                if(max < t->val){                    max = t->val;                }                if(t->left != NULL){                    q.push(t->left);                }                if(t->right != NULL){                    q.push(t->right);                }            }            v.push_back(max);        }        return v;    }