在每个树行中找最大值

 在每个树行中找最大值

题目描述:

前序遍历(Preorder Traversal 亦称先序遍历)——访问根结点的操作发生在遍历其左右子树之前。

需要在二叉树的每一行中找到最大的值。

示例:

输入: 

          1
         /  \
        3   2
       /  \    \  
      5   3   9 

输出: [1, 3, 9]

来源:力扣(LeetCode)
OJ链接

分析:
这道题是层序遍历的扩折, 是在层序层序遍历的基础上在找每一层的最大值, 上代码

class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
	vector<TreeNode*> tq1, tq2;
	vector<int> max;
	TreeNode* cur;
	if (root) tq1.push_back(root);
	int tmpmax;
	while (!tq1.empty() || !tq2.empty()) {
	    for (tmpmax = tq1.front()->val;tq1.size() > 0;) {
	    	cur = tq1.back();
	    	if (cur->val > tmpmax)tmpmax = cur->val;
	    	if (cur->left)tq2.push_back(cur->left);				
                if (cur->right)tq2.push_back(cur->right);
		tq1.pop_back();
            }
	    max.push_back(tmpmax);
	    tq1 = tq2;
	    tq2.clear();
	}
	return max;
    }
};

层序遍历储存上一层节点指针的数据结构还可以是其他, 但vector比较快一点, 比如还可以用双端队列deque
 

class Solution {
public:
   vector<int> largestValues(TreeNode* root) {
       deque<TreeNode*> tq;
       vector<int> max;
       TreeNode* cur;
       if (root) tq.push_back(root);
       int size, tmpmax;
       while (!tq.empty()) {
           size = tq.size();
           for (tmpmax =tq.front()->val; size > 0; --size) {
               cur = tq.front();
               if (cur->val > tmpmax)tmpmax = cur->val;
               if (cur->left)tq.push_back(cur->left);
               if (cur->right)tq.push_back(cur->right);
               tq.pop_front();
           }
           max.push_back(tmpmax);
       }
       return max;
   }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值