剑指Offer:从上往下打印二叉树
来源:互联网 发布:电脑网络监控录像软件 编辑:程序博客网 时间:2024/05/21 13:57
从上往下打印二叉树
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
总觉得这题在LeetCode上面做过,待优化。
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class Solution {public: vector<int> PrintFromTopToBottom(TreeNode *root) { //BFS stack<TreeNode*> st1,st2,st3; vector<int> res{}; if(!root) return res; st1.push(root); while((!st1.empty())||(!st2.empty())){ if(st1.empty()){ while(!(st2.empty())){ TreeNode *cur=st2.top(); st2.pop(); res.push_back(cur->val); st3.push(cur);//st3辅助栈,逆序 // if(cur->right) st1.push(cur->right); // if(cur->left) st1.push(cur->left); } while(!(st3.empty())){ TreeNode *cur=st3.top(); st3.pop(); if(cur->right) st1.push(cur->right); if(cur->left) st1.push(cur->left); } } else{ while(!(st1.empty())){ TreeNode *cur=st1.top(); st1.pop(); res.push_back(cur->val); if(cur->right) st2.push(cur->right); if(cur->left) st2.push(cur->left); } } } return res; }};
0 0
- 剑指offer: 从上往下打印二叉树(树)
- 剑指offer:从上往下打印二叉树
- 剑指offer系列源码-从上往下打印二叉树
- 剑指offer--从上往下打印二叉树
- 剑指Offer之 - 从上往下打印二叉树
- 剑指offer 23 - 从上往下打印二叉树
- 剑指offer之从上往下打印二叉树
- 《剑指offer》之从上往下打印二叉树
- 《剑指offer》从上往下打印二叉树
- 剑指Offer系列---(25)从上往下打印二叉树
- 剑指offer—从上往下打印二叉树
- 剑指Offer-23-从上往下打印二叉树
- 剑指offer:从上往下打印二叉树
- 《剑指offer》——从上往下打印二叉树
- 剑指offer-从上往下打印二叉树
- 剑指offer 22 从上往下打印二叉树
- 【剑指offer系列】 从上往下打印二叉树___23
- 剑指offer面试题 从上往下打印二叉树
- 今天开通了博客
- Robot Framework +Appium的简单教程及实例
- 六度分离
- poj 1185 状态压缩dp-炮兵阵地
- 【Android学习笔记】ExpandableListView镶嵌在viewpager滑动不了或者滑动不全的问题
- 剑指Offer:从上往下打印二叉树
- JAVA错误日志
- Tinyhttpd源码分析
- linux中多路复用poll浅析
- IOS从字符串中获取指定字符之间的字符串
- 漫谈递归
- 排查调用耗时较长的问题
- 机器学习简单实验(学习或运算)
- .NET MVC4+EF环境构建