题目:从上往下打印二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
这题挺简单的。相当于广度优先搜索,考虑用队列来做。如果是深度优先,可以使用堆栈或者采用递归。代码如下:
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) {
vector<int> treeNodeVect;
if(root==NULL)
return treeNodeVect;
queue<TreeNode *> nodeQueue;
TreeNode *treeNode=root;
nodeQueue.push(treeNode);
while(!nodeQueue.empty())
{
treeNode=nodeQueue.front();
nodeQueue.pop();
treeNodeVect.push_back(treeNode->val);
if(treeNode->left)
nodeQueue.push(treeNode->left);
if(treeNode->right)
nodeQueue.push(treeNode->right);
}
return treeNodeVect;
}
};