从上往下打印出二叉树的每个节点,同层节点从左至右打印。
不要忘记判断root==NULL,不要忘记q.pop();
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 14 queue<TreeNode *> q; 15 vector<int> res; 16 TreeNode * tmp=NULL; 17 if(root==NULL) return res; 18 q.push(root); 19 while(!q.empty()){ 20 tmp=q.front(); 21 res.push_back(tmp->val); 22 q.pop(); 23 if(tmp->left!=NULL) 24 q.push(tmp->left); 25 if(tmp->right!=NULL) 26 q.push(tmp->right); 27 } 28 return res; 29 } 30 };
原文:http://www.cnblogs.com/zl1991/p/4764831.html