力扣107. 二叉树的层次遍历 II(层序遍历,队列,广度优先算法,BFS)

力扣107. 二叉树的层次遍历 II(层序遍历,队列,广度优先算法,BFS)

https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其自底向上的层次遍历为:

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

 

层序遍历,队列,广度优先算法,BFS

//层序遍历,队列,广度优先算法,BFS

#include "stdafx.h"
#include<queue>
#include<vector>
#include <iostream>
using namespace std;
struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution
{
public:
	vector<vector<int>> levelOrderBottom(TreeNode* root)
	{
		int curcount = 0;
		int nextcount = 1;
		int depth = 0;
		vector<int>valtemp;
		vector<vector<int>>resulttemp;
		vector<vector<int>>result;
		queue<TreeNode*>que;
		//头结点为空,直接返回空数组
		if (root == nullptr)return result;
		que.push(root);
		while (!que.empty())
		{
			TreeNode* tempnode = que.front(); que.pop();
			curcount++;
			//对于每一个值,先暂存起来
			valtemp.push_back(tempnode->val);
			if (tempnode->left != nullptr)que.push(tempnode->left);
			if (tempnode->right != nullptr)que.push(tempnode->right);
			if (curcount == nextcount)
			{
				//一层存一次
				resulttemp.push_back(valtemp);
				valtemp.clear();
				curcount = 0;
				depth++;
				nextcount = que.size();
			}
		}
		//自底向上,翻转数组
		for (int i = depth - 1; i >= 0; i--)
		{
			result.push_back(resulttemp[i]);
		}
		return result;
	}
};

int main()
{
	TreeNode p[13] = { 2,3,3,4,5,5,4,NULL,NULL,8,9,9,8 };
	p[0].left = &p[1]; p[0].right = &p[2];
	p[1].left = &p[3]; p[1].right = &p[4];
	p[2].left = &p[5]; p[2].right = &p[6];
	//p[3].left = &p[7]; p[3].right = &p[8];
	p[4].left = &p[9]; p[4].right = &p[10];
	p[5].left = &p[11]; p[5].right = &p[12];
	Solution s;
	auto result = s.levelOrderBottom(p);
	for (int i = 0; i < result.size(); i++)
	{
		for (int j = 0; j < result[i].size(); j++)
		{
			cout << result[i][j] << '\t';
		}
		cout << '\n';
	}
	return 0;
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值