之字形打印二叉树
来源:互联网 发布:https的默认端口 编辑:程序博客网 时间:2024/05/20 11:49
一、题目描述(Again !)
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路:
定义两个栈,分别用来保存奇数层结点和偶数层结点,奇数层结点 从左到右打印(所以它们要从右到左进栈),偶数层结点从右到左打印(所以它们要从左到右进栈)。
vector<vector<int> > Print(TreeNode* pRoot) { stack<TreeNode*> st[2]; vector<vector<int> > res; vector<int> path; if(pRoot==NULL) return res; st[0].push(pRoot); TreeNode* outputNode=NULL; int curr=0; while(!st[0].empty() || !st[1].empty()) { outputNode=st[curr].top(); st[curr].pop(); path.push_back(outputNode->val); if(curr==0) { if(outputNode->left!=NULL) st[!curr].push(outputNode->left); if(outputNode->right!=NULL) st[!curr].push(outputNode->right); } else { if(outputNode->right!=NULL) st[!curr].push(outputNode->right); if(outputNode->left!=NULL) st[!curr].push(outputNode->left); } if(st[curr].empty()) { res.push_back(path); path.clear(); curr=!curr; } } return res; }
二、
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int> > res; if(pRoot==NULL) return res; vector<int> level; queue<TreeNode*> que; que.push(pRoot); int toBePrint=1;//当前层还有多少个结点待打印 int nextLevel=0;//下一行有多少个结点 TreeNode* tmp=NULL; while(!que.empty()) { tmp=que.front(); que.pop(); toBePrint--; level.push_back(tmp->val); if(tmp->left!=NULL) { que.push(tmp->left); nextLevel++; } if(tmp->right!=NULL) { que.push(tmp->right); nextLevel++; } if(toBePrint==0) { res.push_back(level); level.clear(); toBePrint=nextLevel; nextLevel=0; } } return res; }
0 0
- 之字形打印二叉树
- 之字形打印二叉树
- 之字形打印二叉树
- 之字形打印二叉树
- 按之字形打印二叉树
- 按照之字形打印二叉树
- 按之字形打印二叉树
- 按之字形打印二叉树
- 二叉树------之字形打印二叉树
- 按之字形顺序打印二叉树
- 二叉树分层遍历(含之字形打印)
- 按之字形顺序打印二叉树
- 按之字形顺序打印二叉树
- 按之字形顺序打印二叉树
- 按之字形顺序打印二叉树
- 牛客网 | 按之字形顺序打印二叉树
- 按之字形顺序打印二叉树
- 按之字形顺序打印二叉树
- 权限管理命令-其他权限管理命令
- Android Api Demos登顶之路(八十四)Graphics-->PolyToPoly
- hihoCoder#1090
- Remove Duplicates from Sorted List II
- 1688配置信息
- 之字形打印二叉树
- AppleTV 不显示 Store 的问题
- hdu5489(删除一段后的最长上升子序列长度)LIS
- block
- 指针与数组
- Demystifying ASM REQUIRED_MIRROR_FREE_MB and USABLE_FILE_MB
- Wireless Network
- OC的内存管理
- poj 3080 Blue Jeans