LeetCode Binary Tree Level Order Traversal
传送门:https://oj.leetcode.com/problems/binary-tree-level-order-traversal/
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
题目大意:二叉树的层序遍历
题目分析:题目要求按层次存入vector<vector<int>>中 这就要求在用队列遍历的同时, 还需要记录当前所在层数, 然后每层存一次。
我的解法:采用BFS, 使用队列, 并记录层数。
/** * Definition for binary tree * 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) { int order = 0, level = 0, next = 0, count = 1; vector<vector<int>> sol; vector<int> row; queue<TreeNode*> q; TreeNode* b; if(root == NULL) return sol; q.push(root); while(!q.empty()){ b = q.front(); q.pop(); row.push_back(b->val); order++; if(b->left != NULL){ q.push(b->left); next++; } if(b->right != NULL){ q.push(b->right); next++; } if(order == count){ level++; order = 0; sol.push_back(row); count = next; next = 0; row.clear(); } } return sol; } };