// stdafx.cpp : 只包括标准包含文件的源文件 // 二叉树构造及遍历1.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中引用任何所需的附加头文件, //而不是在此文件中引用 #include<iostream> #include<vector> #include<deque> using namespace std; typedef struct tree_node_s { char data; struct tree_node_s *lchild; struct tree_node_s *rchild; }tree_node_t, *Tree; void createBitTree(Tree *T) { char c = getchar(); if(c == '#') { *T = NULL; } else { *T = (tree_node_t*)malloc(sizeof(tree_node_t)); (*T)->data = c; createBitTree(&(*T)->lchild); createBitTree(&(*T)->rchild); } } void print_tree(Tree T) { if(T) { cout << T->data << " "; print_tree(T->lchild); print_tree(T->rchild); } } int printBit_at_level(Tree T, int level) { if(!T || level < 0) return 0; if(0 == level) { cout << T->data << " "; return 1; } return printBit_at_level(T->lchild, level - 1) + printBit_at_level(T->rchild, level - 1); } void printBit_by_level_1(Tree T) { int i = 0; for(i = 0; ; i++) { if(!printBit_at_level(T, i)) break; } cout << endl; } void printBit_by_level_2(Tree T) { deque<tree_node_t*> q_first, q_second; q_first.push_back(T); while(!q_first.empty()) { while(!q_first.empty()) { tree_node_t *temp = q_first.front(); q_first.pop_front(); cout << temp->data << " "; if(temp->lchild) q_second.push_back(temp->lchild); if(temp->rchild) q_second.push_back(temp->rchild); } cout << endl; q_first.swap(q_second); } } int main() { Tree T = NULL; createBitTree(&T); print_tree(T); cout << endl; printBit_by_level_3(T); cin.get(); return 0; }
初学数据结构---二叉树层次遍历
最新推荐文章于 2022-10-13 14:59:04 发布