码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-08-22 22:30:39      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   os   io   ar   div   log   

比如下面一棵树

    A

  B       C

D       E  F

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

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

 

#include <iostream>
#include <stack>

struct TreeNode
{
    char data;
    TreeNode* leftChd;
    TreeNode* rightChd;
};

std::stack<TreeNode*> nodeStack;

void printTree(TreeNode* node)
{
    nodeStack.push(node);
    //std::cout << node->data << std::endl;
    if(node->rightChd != NULL)
    {
        printTree(node->rightChd);
    }
    if(node->leftChd != NULL)
    {
        printTree(node->leftChd);
    }
}

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;
}

 

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

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

标签:des   style   blog   color   os   io   ar   div   log   

原文地址:http://www.cnblogs.com/xie-mx/p/3930325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!