-06-22
1.题目描述
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
2.题解
广度优先搜索,即层次遍历即可
3.代码
/*** Definition for a binary tree node.* struct TreeNode {*int val;*TreeNode *left;*TreeNode *right;*TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {public:vector<vector<int>> levelOrder(TreeNode* root) {if (!root) return vector<vector<int>>(0);vector<vector<int>> res;queue<TreeNode*> myque;myque.push(root);while (!myque.empty()){int cnt=myque.size();vector<int> tmp;for (int i=0;i<cnt;i++){TreeNode* t;t=myque.front();myque.pop();tmp.push_back(t->val);if (t->left) myque.push(t->left);if (t->right) myque.push(t->right);}res.push_back(tmp);}return res;}};