// binarytree.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> using namespace std; typedef struct NODE { char ch; NODE* lchild; NODE* rchild; }NODE; void Recursion(NODE* root) { if (root == NULL) return; cout << root->ch << endl; Recursion(root->lchild); Recursion(root->rchild); } void Createbinary() { NODE node1 = { 'A' , NULL , NULL}; NODE node2 = { 'B' , NULL , NULL }; NODE node3 = { 'C' , NULL , NULL }; NODE node4 = { 'D' , NULL , NULL }; NODE node5 = { 'E' , NULL , NULL }; NODE node6 = { 'F' , NULL , NULL }; NODE node7 = { 'G' , NULL , NULL }; NODE node8 = { 'H' , NULL , NULL }; node1.lchild = &node2; node1.rchild = &node6; node2.rchild = &node3; node3.lchild = &node4; node3.rchild = &node5; node6.rchild = &node7; node7.lchild = &node8; Recursion(&node1); } int main() { //std::cout << "Hello World!\n"; Createbinary(); return 0; }
先序遍历结果:
中序遍历:
后序遍历:
//求叶子结点的数目
// binarytree.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> using namespace std; typedef struct NODE { char ch; NODE* lchild; NODE* rchild; }NODE; void Recursion(NODE* root,int* res) { if (root == NULL) return; if (root->lchild == NULL && root->rchild == NULL) { (*res)++; } Recursion(root->lchild,res); Recursion(root->rchild,res); //cout << root->ch << endl; } void Createbinary() { NODE node1 = { 'A' , NULL , NULL}; NODE node2 = { 'B' , NULL , NULL }; NODE node3 = { 'C' , NULL , NULL }; NODE node4 = { 'D' , NULL , NULL }; NODE node5 = { 'E' , NULL , NULL }; NODE node6 = { 'F' , NULL , NULL }; NODE node7 = { 'G' , NULL , NULL }; NODE node8 = { 'H' , NULL , NULL }; node1.lchild = &node2; node1.rchild = &node6; node2.rchild = &node3; node3.lchild = &node4; node3.rchild = &node5; node6.rchild = &node7; node7.lchild = &node8; int leafcount = 0; Recursion(&node1,&leafcount); cout << leafcount; } int main() { //std::cout << "Hello World!\n"; Createbinary(); return 0; }