二叉树的层次遍历 II

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

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

返回其自底向上的层次遍历为:[ [15,7],[9,20],[3]]
程序输出为:
15 7 9 20 3

输入说明 :
首先输入结点的数目n(注意,这里的结点包括题中的null空结点)
然后输入n个结点的数据,需要填充为空的结点,输入null。

输出说明 :
输出结果,每个数据的后面跟一个空格。

输入范例 :
7
3 9 20 null null 15 7

输出范例 :
15 7 9 20 3

#include <iostream>
#include <queue>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include<queue>

using namespace std;
struct TreeNode{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(NULL), right(NULL) {}
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

TreeNode* inputTree(){
    int n,count=0;
    char item[100];
    cin>>n;
    if (n==0)
        return NULL;
    cin>>item;
    TreeNode* root = new TreeNode(atoi(item));
    count++;
    queue<TreeNode*> nodeQueue;
    nodeQueue.push(root);
    while (count<n){
        TreeNode* node = nodeQueue.front();
        nodeQueue.pop();
        cin>>item;
        count++;
        if (strcmp(item,"null")!=0){
            int leftNumber = atoi(item);
            node->left = new TreeNode(leftNumber);
            nodeQueue.push(node->left);
        }
        if (count==n)
            break;
        cin>>item;
        count++;
        if (strcmp(item,"null")!=0){
            int rightNumber = atoi(item);
            node->right = new TreeNode(rightNumber);
            nodeQueue.push(node->right);
        }
    }
    return root;
}

vector<vector<int>> levelOrderBottom(TreeNode* root){
	vector<vector<int>> res(100);
	queue<pair<TreeNode*,int>> q;
	if(root){
		q.push(make_pair(root,0));
	}
	while(!q.empty()){
		TreeNode* node=q.front().first;
		int depth=q.front().second;
		q.pop();
		res[depth].push_back(node->val);
		if(node->left){
			q.push(make_pair(node->left,depth+1));
		}
		if(node->right){
			q.push(make_pair(node->right,depth+1));
		}
	}
	reverse(res.begin(),res.end());
	return res;
}

int main(){
    TreeNode* root;
    root=inputTree();
    vector<vector<int>> res=levelOrderBottom(root);
    for(int i=0; i<res.size(); i++){
        vector<int> v=res[i];
        for(int j=0; j<v.size(); j++)
            cout<<v[j]<<" ";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值