c++ 递归版本遍历二叉树

来源:互联网 发布:深圳旅游知乎 编辑:程序博客网 时间:2024/05/20 23:38
#include <iostream>


struct BinTreeNode {
int value ;
BinTreeNode * leftChild, *rightChild;


BinTreeNode(int data) : value(data), leftChild(nullptr), rightChild(nullptr) {};
};


void preOrderRecur(const BinTreeNode * root);
void midOrderRecur(const BinTreeNode * root);
void lastOrderRecur(const BinTreeNode * root);




int main()
{
BinTreeNode root(5);
BinTreeNode n1(9);
BinTreeNode n2(8);
BinTreeNode n3(7);
BinTreeNode n4(6);
BinTreeNode n5(5);
BinTreeNode n6(4);


root.leftChild = &n1;
root.rightChild = &n4;
n1.leftChild = &n2;
n1.rightChild = &n3;
n3.rightChild = &n6;
n4.leftChild = &n5;


std::cout << "preOrderRecur: ";
preOrderRecur(&root);
std::cout << std::endl;


std::cout << "midOrderRecur: ";
midOrderRecur(&root);
std::cout << std::endl;


std::cout << "lastOrderRecur: ";
lastOrderRecur(&root);
std::cout << std::endl;


system("pause");
return 0;
}


void preOrderRecur(const BinTreeNode * root)
{
if (root == nullptr)
{
return;
}


std::cout << root->value << " ";
preOrderRecur(root->leftChild);
preOrderRecur(root->rightChild);


}


void midOrderRecur(const BinTreeNode * root)
{
if (root == nullptr)
{
return;
}


preOrderRecur(root->leftChild);
std::cout << root->value << " ";
preOrderRecur(root->rightChild);
}
void lastOrderRecur(const BinTreeNode * root)
{
if (root == nullptr)
{
return;
}


preOrderRecur(root->leftChild);
preOrderRecur(root->rightChild);
std::cout << root->value << " ";
}