题目
- Binary Tree Level Order Traversal
Medium
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
思路
记录每一行的最后一个节点,当前节点等于最后一个就换行
/**
* 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) {
queue<TreeNode* > queuePtr;
queuePtr.push(root);
TreeNode * last = root;
TreeNode * nlast = root;
vector<vector<int>> result;
if(root==nullptr)
return result;
vector<int > row;
int N = 0;
while (!queuePtr.empty()) {
TreeNode* nowPter = queuePtr.front();
if (nowPter->left != nullptr) {
queuePtr.push(nowPter->left);
}
if (nowPter->right != nullptr) {
queuePtr.push(nowPter->right);
}
row.push_back(nowPter->val);
if (nowPter == last) {
last = queuePtr.back();
result.push_back(row);
row.clear();
}
queuePtr.pop();
}
return result;
}
};