marcus.x的博客

[二叉树的分层遍历] 倒序的树

比如下面一棵树

    A

  B       C

D       E  F

按照DEFBCA的顺序输出,即倒序分层并按照顺序输出。

答,其实比较简单。我想到的办法是加一个栈,记录每一层的内容,最后输出。可能比较笨,如果有更好的办法,请告诉我。

 

#include <iostream>

#include <stack>

#include <queue>

 

struct TreeNode

{

    char data;

    TreeNode* leftChd;

    TreeNode* rightChd;

};

 

std::stack<TreeNode*> nodeStack;

std::queue<TreeNode*> nodeQueue;

 

void printTree(TreeNode* node)

{

    nodeQueue.push(node);

    while (nodeQueue.size() != 0) {

        TreeNode *tmp = nodeQueue.front();

        if(tmp->rightChd != NULL)

            nodeQueue.push(tmp->rightChd);

        if(tmp->leftChd != NULL)

            nodeQueue.push(tmp->leftChd);

        nodeStack.push(tmp);

        nodeQueue.pop();

    }

}

 

void printStack(std::stack<TreeNode*> test)

{

    while(test.size() != 0)

    {

        std::cout << test.top()->data << std::endl;

        test.pop();

    }

}

 

int main(int argc, const char * argv[])

{

    TreeNode *a = new TreeNode;

    a->TreeNode::data = 'A';

    TreeNode *b = new TreeNode;

    b->TreeNode::data = 'B';

    TreeNode *c = new TreeNode;

    c->TreeNode::data = 'C';

    TreeNode *d = new TreeNode;

    d->TreeNode::data = 'D';

    TreeNode *e = new TreeNode;

    e->TreeNode::data = 'E';

    TreeNode *f = new TreeNode;

    f->TreeNode::data = 'F';

    a->leftChd = b;

    a->rightChd = c;

    b->leftChd = d;

    c->leftChd = e;

    c->rightChd =f;

    std::cout << "Hello, MAC!\n";

    printTree(a);

    printStack(nodeStack);

    return 0;

}

 

我写的不是很好,希望跟各位多多交流。

posted on 2014-08-22 22:08  marcus.x  阅读(350)  评论(0编辑  收藏  举报

导航