C言語二叉木の非再帰遍歴

12236 ワード

#include 
#include 
using namespace std;

/*
	1、         
	2、    size> 0      
		2.1       
		2.2                              
		2.3        flag     
		2.4                        
		2.5        
*/

typedef struct BinaryTree {
    int value;
    struct BinaryTree* Left;
    struct BinaryTree* Right;
    bool flag;  
}BinaryTrees;

void pre_trial(BinaryTrees *p_node) {
    stack<BinaryTrees *> stack_help;
    stack_help.push(p_node);
    while(stack_help.size() > 0){
        BinaryTrees *node_help = stack_help.top();
        stack_help.pop();
        if(node_help -> flag) {
            cout << node_help -> value << " ";
            continue;
        } else {
            node_help -> flag = true;
            //    
            if(node_help -> Right != NULL)
                stack_help.push(node_help -> Right);
            if(node_help -> Left != NULL)
                stack_help.push(node_help -> Left);
            stack_help.push(node_help);

            //    
            //if(node_help -> Right != NULL)
                //stack_help.push(node_help -> Right);
            //stack_help.push(node_help);
            //if(node_help -> Left != NULL)
                //stack_help.push(node_help -> Left);

            //    
            //stack_help.push(node_help);
            //if(node_help -> Right != NULL)
                //stack_help.push(node_help -> Right);
            //if(node_help -> Left != NULL)
                //stack_help.push(node_help -> Left);
        }
    }
}

int main() {
    BinaryTrees n1 = {1, NULL, NULL, false};
    BinaryTrees n2 = {2, NULL, NULL, false};
    BinaryTrees n3 = {3, NULL, NULL, false};
    BinaryTrees n4 = {4, NULL, NULL, false};
    BinaryTrees n5 = {5, NULL, NULL, false};
    BinaryTrees n6 = {6, NULL, NULL, false};
    BinaryTrees n7 = {7, NULL, NULL, false};
    BinaryTrees n8 = {8, NULL, NULL, false};
    n1.Left = &n2;
    n1.Right = &n3;
    n2.Left = &n4;
    n2.Right = &n5;
    n3.Left = &n6;
    n3.Right = &n7;
    n4.Left = &n8;
    pre_trial(&n1);
    system("pause");
    return 0;
}