您的位置:首页 > 其它

Binary Tree Level Order Traversal II

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

构造函数的名字和类名相同,没有返回类型;

构造函数有一个(可能为空的)参数列表和一个可能为空的函数体;

构造函数不能被声明成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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: