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]
]
BFS
去跑樹的結構即可。queue
去存左子樹和右子樹,同時也去紀錄子樹的level
。每次從queue
裡面拿新的點來跑,直到queue
為空。
/**
* 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:
void BFS(vector<vector<int>>& ans,vector<int>& nodes,vector<pair<TreeNode*,int>>& queue,int &level)
{
//take new node from queue
pair<TreeNode*,int> n = queue.front();
queue.erase(queue.begin());
if(!n.first)return;
//check level
if(level==n.second)
nodes.push_back(n.first->val);
else
{
level = n.second;
ans.push_back(nodes);
nodes.clear();
nodes.push_back(n.first->val);
}
//push next node into queue
queue.push_back(pair<TreeNode*,int>(n.first->left,n.second+1));
queue.push_back(pair<TreeNode*,int>(n.first->right,n.second+1));
//run until queue is empty
while(queue.size()!=0)
BFS(ans,nodes,queue,level);
//check last level is pushed
if(nodes.size()!=0)
{
ans.push_back(nodes);
nodes.clear();
}
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
vector<int> nodes;
int level=0;
vector<pair<TreeNode*,int>> queue(1,pair<TreeNode*,int>(root,0));
BFS(ans,nodes,queue,level);
return ans;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up