#include "stdafx.h"
#include "tree.h"
#define MAX_TREENODES 10000
TestTree::TestTree(int val)
{
pHeadNode = new NODE();
pHeadNode->value = val;
pHeadNode->pLeftNode = NULL;
pHeadNode->pRightNode = NULL;
}
TestTree::~TestTree()
{
printf("/n");
destroyTree(pHeadNode);
pHeadNode = NULL;
}
bool TestTree::push_LeftChild(int val)
{
NODE *pNode = new NODE();
pNode->value = val;
pNode->pLeftNode = NULL;
pNode->pRightNode = NULL;
if(pHeadNode != NULL)
{
push_LeftNode(pHeadNode,pNode);
return true;
}
return false;
}
void TestTree::push_LeftNode(NODE *pFNode,NODE *pNode)
{
if (pFNode->pLeftNode == NULL)
{
pFNode->pLeftNode = pNode;
return;
}
if (pFNode->pLeftNode != NULL)
{
push_LeftNode(pFNode->pLeftNode, pNode);
return;
}
if (pFNode->pRightNode != NULL)
{
push_RightNode(pFNode->pRightNode, pNode);
return;
}
}
void TestTree::push_RightNode(NODE *pFNode,NODE *pNode)
{
if (pFNode->pRightNode == NULL)
{
pFNode->pRightNode = pNode;
return;
}
if (pFNode->pRightNode != NULL)
{
push_RightNode(pFNode->pRightNode, pNode);
return;
}
if (pFNode->pLeftNode != NULL)
{
push_LeftNode(pFNode->pLeftNode, pNode);
return;
}
}
bool TestTree::push_RightChild(int val)
{
NODE *pNode = new NODE();
pNode->value = val;
pNode->pLeftNode = NULL;
pNode->pRightNode = NULL;
if (pHeadNode)
{
push_RightNode(pHeadNode, pNode);
return true;
}
return false;
}
void TestTree::visit(NODE *treeNode)
{
printf("%d/t",treeNode->value);
}
void TestTree::walkTree()
{
NODE *pNode = pHeadNode;
NODE * NodeStack[MAX_TREENODES];
NODE ** pNodeStack = NULL;
if (pNode)
{
NodeStack[0] = NULL;
pNodeStack = NodeStack + 1;
for (;;)
{
/*如果遍历的节点有左节点把该节点保存到堆栈中,
然后从左节点开始遍历左子树,重复以上的操作,
直到没有左节点的节点*/
while (pNode->pLeftNode !=NULL)
{
*pNodeStack++ = pNode;
pNode = pNode->pLeftNode;
}
for (;;)
{
//*visit 没有左节点的节点
visit(pNode);
if (pNode->pRightNode != NULL)
{
//如果该节点的有右节点,
//从右节点开始循环遍历左子树
pNode = pNode->pRightNode;
break;
}
//如果没有右节点
//从堆栈里取出该节点的父节点
if ((pNode = *--pNodeStack) == NULL)
{
//如果父节点为空该节点是根节点遍历结束
return;
}
}
}
}
}
void TestTree::destroyTree(NODE *pNode)
{
if (pNode != NULL)
{
if (pNode->pLeftNode != NULL)
{
destroyTree(pNode->pLeftNode);
}
if (pNode->pRightNode != NULL)
{
destroyTree(pNode->pRightNode);
}
printf("detele %d/t" ,pNode->value);
delete pNode;
pNode = NULL;
}
}
void TestTree::recursiveWalkTree()
{
walkTree(pHeadNode);
}
void TestTree::walkTree(NODE * pNode)
{
if (pNode != NULL)
{
if (pNode->pLeftNode != NULL)
{
walkTree(pNode->pLeftNode);
}
visit(pNode);
if (pNode->pRightNode != NULL)
{
walkTree(pNode->pRightNode);
}
}
}