L102: 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).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
解题思路:与BFS差不多,只不过要增加一个挡板标识区分每一层
//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) {
vector<vector<int>> levelOrdVec;
if(root == 0)
return levelOrdVec;
queue<TreeNode*> nodeQueue;
TreeNode* mark = nullptr;
nodeQueue.push(root);
while(!nodeQueue.empty())
{
nodeQueue.push(mark);
vector<int> ordVec;
TreeNode* node = nullptr;
while((node = nodeQueue.front()) != mark)
{
nodeQueue.pop();
ordVec.push_back(node->val);
if(node->left) nodeQueue.push(node->left);
if(node->right) nodeQueue.push(node->right);
}
nodeQueue.pop(); //pop mark
levelOrdVec.push_back(ordVec);
}
return move(levelOrdVec);
}
};
时间: 2024-12-18 03:22:13