22从上到下打印二叉树
1 从上到下打印二叉树 2 //题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印。 3 ////思路:其实就是广度优先遍历思想,即层次遍历 4 struct TreeNode 5 { 6 int val; 7 TreeNode* left; 8 TreeNode* right; 9 TreeNode(int x):val(x), left(NULL), right(NULL) 10 { 11 12 } 13 }; 14 class Solution 15 { 16 public: 17 vector<int> PrintFromTopToBottom(TreeNode* root) 18 { 19 if (root == NULL) 20 { 21 return {}; 22 } 23 vector<int> tmpVec; 24 if (root != NULL) 25 { 26 queue<TreeNode*> q; 27 q.push(root); 28 while(!q.empty()) 29 { 30 TreeNode* node = q.front(); 31 q.pop(); 32 tmpVec.push_back(node->val); 33 if (node->left != NULL) 34 { 35 q.push(node->left); 36 } 37 if (node->right != NULL) 38 { 39 q.push(node->right); 40 } 41 } 42 } 43 return tmpVec; 44 } 45 };
在代码的世界尽情的翱翔吧!