Code
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <stack>
#include <queue>
using namespace std;
typedef struct BinaryTree
{
int val;
struct BinaryTree *Lchild;
struct BinaryTree *Rchild;
} binaryTree;
static int idx = 0;
char list[] = {'A', 'B', 'D', '#', '#', 'E', '#', '#', 'C', 'F','#', '#', 'G', '#', '#'};
void depthSearch(binaryTree *root)
{
if(NULL == root) return ;
stack<binaryTree*> myStack;
myStack.push(root);
binaryTree* node;
while(!myStack.empty()){
node = myStack.top();
printf("%c\t", node->val);
myStack.pop();
if(node->Rchild)
{
myStack.push(node->Rchild);
}if(node->Lchild)
myStack.push(node->Lchild);
}
printf("\n");
}
void widthSearch(binaryTree * root)
{
if(NULL == root) return ;
queue<binaryTree*> myQueue;
myQueue.push(root);
binaryTree * node;
while(!myQueue.empty()){
node = myQueue.front();
printf("%c\t", node->val);
myQueue.pop();
if(node->Lchild)
myQueue.push(node->Lchild);
if (node->Rchild)
myQueue.push(node->Rchild);
}
printf("\n");
}
void CreateBinaryTree(binaryTree* &root, char *list)
{
char e = list[idx++];
if(e == '#'){
root = NULL;
} else{
root = (binaryTree*)malloc(sizeof(binaryTree));
if(root == NULL) {
printf("malloc() failed\n");
}
root->val = e;
CreateBinaryTree(root->Lchild, list);
CreateBinaryTree(root->Rchild, list);
}
}
int main() {
binaryTree* tree;
CreateBinaryTree(tree, list);
printf("深度优先遍历二叉树结果: ");
depthSearch(tree);
printf("\n\n广度优先遍历二叉树结果: ");
widthSearch(tree);
printf("\n");
return 0;
}
Result