Binary Tree Level Order Traversal II(LeetCode)

题目来源:leetcode

原题地址:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/

题目:

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

难度级别:
easy(容易)

思路分析:
此题较为简单,采用队列的数据结构就可以很轻松的解决此题。
相对于层序遍历,这里要求对每一层的个数做一下记录就可以了。
然后一层一层遍历就可以完成此题。

实现代码:
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

class Solution
{
public:
	vector<vector<int> > levelOrderBottom(TreeNode* root)
	{
		vector<vector<int> > matrix;
		vector<int> temp;
		if (root == NULL)
		{
			return matrix;
		}
		queue<TreeNode *> tque;
		tque.push(root);
		//temp.push_back(root->val);
		//matrix.push_back(temp);
		TreeNode *p = NULL;
		while (!tque.empty())
		{
			int levelSize = tque.size();
			temp.clear();
			for (int i = 0; i < levelSize; i++)
			{
				p = tque.front();
				tque.pop();
				if (p->left != NULL)
				{
					tque.push(p->left);
				}
				if (p->right != NULL)
				{
					tque.push(p->right);
				}
				temp.push_back(p->val);
			}
			matrix.push_back(temp);
		}
	    int start = 0, end = matrix.size()-1;
	    while (start < end)
	    {
	        temp = matrix[start];
	        matrix[start] = matrix[end];
	        matrix[end] = temp;
	        start++; end--;
	    }
		return matrix;
	}
};



代码说明:
在实现代码中,采用STL模板中的队列来进行辅助计算,每一层循环都先读取队列长度,作为内存循环的次数,此即每层的个数。
需要注意的是,题目中要求结果为从上到下的顺序排序,而vector模板的push_back函数每次是将新元素添加至末尾,所以还需要进行一次对调工作。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值