// BinTree.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include<iostream>
//the struct of the Node
struct binNode{
int data;
binNode *leftNode;
binNode *rightNode;
};
class binaryTree
{
public:
unsigned int nodeNum;
unsigned int treeDepth;
unsigned int leafNum;
binNode *root;
binaryTree(){
root = NULL;
}
void createBinaryTree(int data);
void preOrder(binNode *curNod); //root-left-right
void inOrder(binNode *curNod); //left-root-right
void postOrder(binNode *curNod); //left-right-root
int count(binNode *curNod);
int count();
int findLeaf(binNode *curNod); //get the number of leaves
int findNode(binNode *curNod); //
protected:
private:
};
void binaryTree::createBinaryTree(int dataNew)
{
binNode *newNode = new binNode;
newNode->data = dataNew;
newNode->rightNode = newNode->leftNode = NULL;
if(root == NULL)
root = newNode;
else
{
binNode *curNode = root;
binNode *preNode = NULL;
while ( NULL != curNode )
{
preNode = curNode;
if (dataNew < curNode->data)
curNode = curNode->leftNode;
else
curNode = curNode->rightNode;
}
if (dataNew < preNode->data)
preNode->leftNode = newNode;
else
preNode->rightNode = newNode;
}
}
int binaryTree::count()
{
return binaryTree::count(root);
}
int binaryTree::count(binNode *p)
{
if(p == NULL)
return 0;
else
return count(p->leftNode) + count(p->rightNode) + 1;
}
void binaryTree::preOrder(binNode *curNode)
{
if(curNode != NULL)
{
std::cout<<curNode->data<<" ";
preOrder(curNode->leftNode);
preOrder(curNode->rightNode);
}
}
void binaryTree::postOrder(binNode *curNode)
{
if(curNode != NULL)
{
postOrder(curNode->leftNode);
postOrder(curNode->rightNode);
std::cout<<curNode->data<<" ";
}
}
void binaryTree::inOrder(binNode *curNode)
{
if(curNode != NULL)
{
inOrder(curNode->leftNode);
std::cout<<curNode->data<<" ";
inOrder(curNode->rightNode);
}
}
int binaryTree::findLeaf(binNode *curNode)
{
if ( curNode == NULL)
return 0;
else
{
if ( (curNode->leftNode != NULL) || (curNode->rightNode != NULL ) )
{
findLeaf(curNode->leftNode);
findLeaf(curNode->rightNode);
}
else
{
binaryTree::leafNum ++;
std::cout<<curNode->data<<" ";
}
return binaryTree::leafNum;
}
}
void main()
{
binaryTree myBinaryTree;
int array[]={7,4,2,3,15,35,6,45,55,20,1,14,56,57,58};
unsigned int nodeNum = sizeof(array)/sizeof(array[0]);
myBinaryTree.nodeNum = nodeNum;
std::cout<<"create a binary tree by order: "<<std::endl;
for(int i = 0; i < nodeNum; i++){
std::cout<<array[i]<<" ";
myBinaryTree.createBinaryTree(array[i]);
}
std::cout<<std::endl;
std::cout<<myBinaryTree.count(myBinaryTree.root)<<std::endl;
std::cout<<myBinaryTree.count()<<std::endl;
myBinaryTree.postOrder(myBinaryTree.root);
std::cout<<std::endl;
myBinaryTree.inOrder(myBinaryTree.root);
std::cout<<std::endl;
unsigned int leafNum = myBinaryTree.findLeaf(myBinaryTree.root);
std::cout<<"leaf number:"<<leafNum<<std::endl;
}
c++二叉樹
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.