1. 程式人生 > >二叉樹先序建樹及先序遍歷

二叉樹先序建樹及先序遍歷

#include<iostream>  
using namespace std;  

int N = 0;
typedef struct node  
{  
    struct node *leftChild;  
    struct node *rightChild;  
    char data;  
}BiTreeNode, *BiTree;  
 
//先序建立二叉樹 
void createBiTree(BiTree &T,char array[])  
{  
    char c;  
    c = array[N];  
		N++;
    if('#' == c)  
        T = NULL;  
    else  
    {	if(T==NULL){
		return ;
		}
		else{
        T = new BiTreeNode;  
        T->data = c;  
        createBiTree(T->leftChild,array);  
        createBiTree(T->rightChild,array);  
		}  
	}

}  
  
//先序遍歷二叉樹
void printTree(BiTree &T){
	if(T==NULL){
		return ;
	}else{
	printf("%c\n",T->data);
	printTree(T->leftChild);
	printTree(T->rightChild);
	}
}
int main()  
{  
	char treeArray[15] = {'a','b','d','#','#','e','#','#','c','f','#','#','j','#','#'};
    BiTree T;  
    createBiTree(T,treeArray);  
	printTree(T);
    return 0;  
}