题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
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> v; 14 queue<TreeNode *> q; 15 TreeNode *p = root; 16 while (p || !q.empty()){ 17 v.push_back(p->val); 18 if (p->left) 19 q.push(p->left); 20 if (p->right) 21 q.push(p->right); 22 if (q.empty()) 23 break; 24 p = q.front(); 25 q.pop(); 26 } 27 return v; 28 } 29 };