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