二叉树的遍历
来源:互联网 发布:函数式编程的优点 编辑:程序博客网 时间:2024/06/15 23:38
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class TreeToSequence {public: vector<vector<int> > convert(TreeNode* root) { vector<vector<int> > output; vector<int> iteration; first(root,iteration); output.push_back(iteration); iteration.clear(); middle(root,iteration); output.push_back(iteration); iteration.clear(); last(root,iteration); output.push_back(iteration); iteration.clear(); return output; } void first(TreeNode* root,vector<int> &iteration) { stack<TreeNode*> store; TreeNode* current=NULL; store.push(root); while(!store.empty()) { current=store.top(); iteration.push_back(current->val); store.pop(); if(current->right!=NULL)store.push(current->right); if(current->left!=NULL)store.push(current->left); } } void middle(TreeNode* root,vector<int> &iteration) { stack<TreeNode*> store; TreeNode* current=root; while(!store.empty()||current!=NULL) { if(current!=NULL) { store.push(current); current=current->left; } else { current=store.top(); iteration.push_back(current->val); current=current->right; store.pop(); } } } void last(TreeNode* root,vector<int> &iteration) { stack<TreeNode*> store1,store2; TreeNode* current=NULL; store1.push(root); while(!store1.empty()) { current=store1.top(); store2.push(current); store1.pop(); if(current->left!=NULL)store1.push(current->left); if(current->right!=NULL)store1.push(current->right); } while(!store2.empty()) { iteration.push_back(store2.top()->val); store2.pop(); } }};
阅读全文
1 0
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- Java 多线程卖票例子
- Codeforce_832B_Petya and Exam_字符串模拟
- 配置多个数据源
- 剑指offer-13:在O(1)时间删除链表结点
- 欢迎使用CSDN-markdown编辑器
- 二叉树的遍历
- CSU-ACM2017暑期训练16-树状数组 F
- 二叉树中和为某一值的路径
- 一头坑进Redis之入门
- springmvc中的视图模型的返回方式,尤其注意当返回值为空时的默认视图返回路径
- 守护进程
- fastjson使用
- 选择_冒泡 排序法
- CSS之弹性布局