图(广度优先搜索)515. Find Largest Value in Each Tree Row[Middle]

题目:

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]

找到二叉树每行最大的数。


分析:

第一眼看过去,题目要求一行一行找最大,自然想到 [bfs]:




不过课本上的bfs使用了queue来装节点,虽然一层一层地插入了,可是好像不能很明显地分出层次。如果解决了这个问题,接下来只要对每一层进行排序,选取最大数就好(可以用stl里的sort)。我的解决方法是,在遍历新的一层时,先把节点读到一个容器里,然后再转移到用来递归的容器。


代码:

/**
 * 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 {
public:

//bfs 递归,father是装遍历节点的容器,就是课本(博客上文图片)上的q,res装每一层的值
 void addQueue(vector<vector<int> >&res, vector<TreeNode*>&father) {

    //(1)
    //father不空,还有节点未遍历
	 if (!father.empty()) {
		 vector<TreeNode*> son; //装每一层的节点,然后转移给father
		 vector<int> son2;  //装节点的值,转移到res
		 while (!father.empty()) {
			 TreeNode* fir = father.front();
			 if (fir->left != NULL)
				 son.push_back(fir->left);
			 if (fir->right != NULL)
				 son.push_back(fir->right);

			 father.erase(father.begin());
		 }

		 vector<TreeNode*>::iterator it = son.begin();  //把节点值取出给son2
		 while (it != son.end()) {

			 TreeNode* fir = *it;
			 son2.push_back(fir->val);
			 ++it;
		 }
        
        //(2)
		 if(!son2.empty())
		 res.push_back(son2);

        //son的节点转移到father,进行一次新的遍历
		 while (!son.empty()) {
			 father.push_back(son.front());
			 son.erase(son.begin());
		 }
		 addQueue(res, father);
	 }

 }

//为sort逆序排序提供的函数
 static bool com(int a, int b) {
	 return a > b;
 }

//
vector<int> largestValues(TreeNode* root) {
     vector<vector<int> >res;
	 vector<TreeNode*> father;
	 vector<int> son2;

	 if (root != NULL) {
		 father.push_back(root);
		 son2.push_back(root->val);


		 res.push_back(son2);
	 }

	 addQueue(res, father);

	 vector<int> hhh;

	 for (int i = 0; i < res.size(); i++) {
		 sort(res[i].begin(), res[i].end(),com); //(3)
		 hhh.push_back(res[i].front());
	 }
	 
	 return hhh;
    }
};




注释解释:

(1):bfs里用vector代替了queue,这是为了后面操作方便决定的,因为sort要输入容器迭代器来排序,但是queue没有

(2):

 if(!son2.empty())


这句是因为sort排序对象不能为空

(3)sort可以传递函数指针(代码中的com),关于函数指针和函数对象的具体用法参见:点击打开链接


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值