class ReverseStack {
public:
int level = 0;
vector<int> reverseStackRecursively(vector<int> stack, int top) {
// write code here
if(top > 0){
int val = stack[top - 1];
++level;
stack = reverseStackRecursively(stack, top - 1);
--level;
stack[level] = val;
}
return stack;
}
};
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行
思路:
A
/ \
B C
/ / \
D E F
A
B C
D E F
按照层序遍历的思想,统计出每层结点的个数,然后打印。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > ret;
if(pRoot==NULL)
return ret;
queue<TreeNode*> q;
q.push(pRoot);
while(!q.empty()){
vector<int> tmp;
int i=0,len=q.size();
while(i<len){
TreeNode *front=q.front();
tmp.push_back(front->val);
if(front->left)
q.push(front->left);
if(front->right)
q.push(front->right);
q.pop();
i++;
}
ret.push_back(tmp);
}
return ret;
}
};