标签: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