首页 > 代码库 > [二叉树的分层遍历] 倒序的树
[二叉树的分层遍历] 倒序的树
比如下面一棵树
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 = http://www.mamicode.com/‘A‘; TreeNode *b = new TreeNode; b->TreeNode::data = http://www.mamicode.com/‘B‘; TreeNode *c = new TreeNode; c->TreeNode::data = http://www.mamicode.com/‘C‘; TreeNode *d = new TreeNode; d->TreeNode::data = http://www.mamicode.com/‘D‘; TreeNode *e = new TreeNode; e->TreeNode::data = http://www.mamicode.com/‘E‘; TreeNode *f = new TreeNode; f->TreeNode::data = http://www.mamicode.com/‘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;}
我写的不是很好,希望跟各位多多交流。
[二叉树的分层遍历] 倒序的树
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。