Binary Tree Level Order Traversal II

基础知识:构造函数的任务是初始化类对象的数据成员,无论何时只要类的对象被创建,就会执行构造函数。

  • 构造函数的名字和类名相同,没有返回类型;
  • 构造函数有一个(可能为空的)参数列表和一个可能为空的函数体;
  • 构造函数不能被声明成const 的。
  • 默认构造函数:Sales_data()=defaut;
  • 构造函数初始值列表:
    Sales_data(const std::string &s,unsigned n,double p):bookNo(s),units_sold(n),revenue(p*n) {}
    其中花括号为空函数体,花括号后面不需要分号。其中bookNo、units_sold和revenue后面的()中为成员初始值,这里小括号可以替换为花括号。
    这里写图片描述
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
#include<stdio.h>
using namespace std;

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

typedef TreeNode* BinaryTree;
vector<vector<int> > res;

void DFS(TreeNode* root, int level)
{
    if (root == NULL) return;
    if (level == res.size())  //The level does not exit in output
    {
        res.push_back(vector<int>()); //Create a new level
    }

    res[level].push_back(root->val);  //Add the current value to its level
    DFS(root->left, level+1);  //Go to the next level
    DFS(root->right,level+1);
}

void CreateBinaryTree(BinaryTree &T)
{   
    char ch;
    scanf_s("%c",&ch);
    if (ch == '#')
        T = NULL;
    else{
            T = (TreeNode *)malloc(sizeof(TreeNode));
            int d = atoi(&ch);
            T->val = d;         //生成根结点
            CreateBinaryTree(T->left);   //构造左子树
            CreateBinaryTree(T->right);             //构造右子树 
          }     
}



vector<vector<int> > levelOrderBottom(TreeNode* root){

    DFS(root,0);
    return vector<vector<int> >(res.rbegin(),res.rend());
}




int main()
{
    BinaryTree T=NULL;
    CreateBinaryTree(T);
    res = levelOrderBottom(T);
    for (int i = 0; i != res.size(); i++)
    {
        for (int j = 0; j != res[i].size(); j++)
        {
            cout << res[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

当输入为:123##45#7##6###
输出:
7
5 6
3 4
2
1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值