19,按层次输出二叉树的节点《剑指Offer》
题目:
按层次输出二叉树的节点,同一层次按从左到右
思路:
层次遍历,一个队列解决
代码:
/* 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> res; queue<TreeNode*> q; TreeNode *tmpNode; if(root==NULL){ //首节点为空就弹出 return res; }else{ q.push(root); } while(!q.empty()){ tmpNode=q.front(); q.pop(); res.push_back(tmpNode->val); if(tmpNode->left!=NULL) q.push(tmpNode->left); if(tmpNode->right!=NULL) q.push(tmpNode->right); } return res; } };