重温了一下二叉树这个结构,以前上课的时候都是感觉懂了,具体实现还没有动手写过。主要写了二叉树的建立,递归遍历以及深度,根节点等方法。
//树节点的头文件
#ifndef BinTreeNode_H_
#define BinTreeNode_H_
#define NULL 0
class BinTreeNode
{
public:
char data;
BinTreeNode* leftChild; //左子树
BinTreeNode* rightChild;//右子树
public:
BinTreeNode();
BinTreeNode(char item);//带参构造函数
};
#endif
#include "BinTreeNode.h"
BinTreeNode::BinTreeNode()
{
}
BinTreeNode::BinTreeNode(char item)
{
data=item;
leftChild=NULL;
rightChild=NULL;
}
#ifndef BinTree_H_
#define BinTree_H_
#include "BinTreeNode.h"
class BinTree
{
public:
BinTree();
BinTreeNode *getRoot();
int getdepth(BinTreeNode* );
void createTree(BinTreeNode* &);//构造二叉树,传递的是指针的引用
void preorderTraversal(BinTreeNode* &);//先序递归遍历
void inorderTraversal(BinTreeNode* &);//中序递归遍历
void postorderTraversal(BinTreeNode* &);//后续递归遍历
private:
BinTreeNode *root;
int depth;
};
#endif
#include "BinTree.h"
#include <iostream>
using namespace std;
BinTree::BinTree()
{
root =NULL;
}
BinTreeNode* BinTree::getRoot()
{
return root;
}
void BinTree::createTree(BinTreeNode* &treeNode)
{
char item;
cin>>item;
if(item==‘0‘)
{
treeNode=NULL;
}
else
{
treeNode=new BinTreeNode(item);
if(root==NULL)
{
root=treeNode;
}
createTree(treeNode->leftChild);
createTree(treeNode->rightChild);
}
}
void BinTree::preorderTraversal(BinTreeNode * ¤tNode)
{
cout<<currentNode->data<<" ";
if(currentNode->leftChild!=NULL)
preorderTraversal(currentNode->leftChild);
if(currentNode->rightChild!=NULL)
preorderTraversal(currentNode->rightChild);
// if(currentNode)
// {
// cout<<currentNode->data<<" ";
// preorderTraversal(currentNode->leftChild);
// preorderTraversal(currentNode->rightChild);
// }
}
void BinTree::inorderTraversal(BinTreeNode * ¤tNode)
{
if(currentNode!=NULL)
{
inorderTraversal(currentNode->leftChild);
cout<< currentNode->data<<" ";
inorderTraversal(currentNode->rightChild);
}
}
void BinTree::postorderTraversal(BinTreeNode* ¤tNode)
{
if(currentNode!=NULL)
{
postorderTraversal(currentNode->leftChild);
postorderTraversal(currentNode->rightChild);
cout<<currentNode->data<<" ";
}
}
int BinTree::getdepth(BinTreeNode* parentNode)//获取二叉树的深度
{
if(parentNode==NULL)
return 0;
int ldepth=getdepth(parentNode->leftChild);
int rdepth=getdepth(parentNode->rightChild);
if(ldepth>=rdepth) return (ldepth+1);
return (rdepth+1);
}
#include "BinTree.h"
#include <iostream>
using namespace std;
int main()
{
BinTree binTree;
BinTreeNode * node=new BinTreeNode;
cout<<"请输入二叉树节点(例如:ab00c00)";
binTree.createTree(node);
binTree.preorderTraversal(node);
cout<<endl;
binTree.inorderTraversal(node);
cout<<endl;
binTree.postorderTraversal(node);
cout<<endl;
BinTreeNode *root=binTree.getRoot();
cout<<root->data;
cout<<binTree.getdepth(node);
return 0;
}