题目链接:从上往下打印二叉树
题意:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
题解:层序遍历啊。借助一个队列,从根结点开始,每次输出一个,就压入它的左右子节点。
代码:
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 };*/ 10 class Solution { 11 public: 12 vector<int> PrintFromTopToBottom(TreeNode* root) { 13 vector<int> ans; 14 queue<TreeNode*> q; 15 TreeNode* node; 16 if(root == NULL) return ans; 17 18 q.push(root); 19 while(!q.empty()){ 20 node = q.front(); 21 ans.push_back(node->val); 22 if(node->left) q.push(node->left); 23 if(node->right) q.push(node->right); 24 q.pop(); 25 } 26 return ans; 27 } 28 };