#include<stdio.h>
#include<stdlib.h>
#include<stack>
using namespace std;
typedef struct TreeNode* BinTree;
struct TreeNode
{
int data;
BinTree Left;
BinTree Right;
};
bool creatBinTree(BinTree &BT)
{
printf("请输入当前节点数据\n");
char ch;
scanf(" %c", &ch);
if (ch == '*')
BT = NULL;
else
{
BT = (BinTree)malloc(sizeof(TreeNode));
BT->data = ch - '0';
creatBinTree(BT->Left);
creatBinTree(BT->Right);
}
return true;
}
void preOrder(BinTree BT)
{
if (BT != NULL)
{
printf("%d\n", BT->data);
preOrder(BT->Left);
preOrder(BT->Right);
}
}
void inOrder(BinTree BT)
{
if (BT != NULL)
{
inOrder(BT->Left);
printf("%d\n", BT->data);
inOrder(BT->Right);
}
}
void postOrder(BinTree BT)
{
if (BT != NULL)
{
postOrder(BT->Left);
postOrder(BT->Right);
printf("%d\n", BT->data);
}
}
void inOrder2(BinTree BT)
{
stack<TreeNode*> S;
BinTree p = BT;
while (p!=NULL || !S.empty())
{
if (p != NULL)
{
S.push(p);
p = p->Left;
}
else
{
p = S.top();
S.pop();
printf("%d\n", p->data);
p = p->Right;
}
}
}
void preOrder2(BinTree BT)
{
stack<TreeNode*> S;
BinTree p = BT;
while (p != NULL || !S.empty())
{
if (p != NULL)
{
printf("%d\n", p->data);
S.push(p);
p = p->Left;
}
else
{
p = S.top();
S.pop();
p = p->Right;
}
}
}
int postOrderGetHeight(BinTree BT)
{
int hL, hR, maxH;
if (BT != NULL)
{
hL = postOrderGetHeight(BT->Left);
hR = postOrderGetHeight(BT->Right);
maxH = hL > hR ? hL : hR;
return maxH + 1;
}
else
return 0;
}
int main()
{
BinTree BT;
creatBinTree(BT);
printf("递归遍历结果\n");
inOrder(BT);
printf("非递归遍历结果\n");
inOrder2(BT);
return 0;
}
二叉搜索树查找元素
TreeNode* find(int elem, BinTree BT)
{
if (BT == NULL)
return NULL;
if (elem > BT->data)
return find(elem, BT->Right);
else if (elem < BT->data)
return find(elem, BT->Left);
else
return BT;
}
TreeNode* find2(int elem, BinTree BT)
{
while (BT!=NULL)
{
if (elem > BT->data)
BT = BT->Right;
else if (elem < BT->data)
BT = BT->Left;
else
return BT;
}
return NULL;
}
|