leetcode 102. Binary Tree Level Order Traversal
本帖最后由 Seawolf 于 2019-10-3 05:43 编辑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
/ \
920
/\
15 7
return its level order traversal as:
[
,
,
]
/**
* 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) {
// return BFS(root);
vector<vector<int>> ans;
DFS(root,0, ans);
return ans;
}
private:
vector<vector<int>> BFS(TreeNode* root){
vector<vector<int>> ans;
if(root == NULL) return ans;
vector<TreeNode*> cur, next;
cur.push_back(root);
while(!cur.empty()){
ans.push_back({});
for(TreeNode* node : cur){
ans.back().push_back(node->val);
if(node->left != NULL) next.push_back(node->left);
if(node->right != NULL) next.push_back(node->right);
}
cur.swap(next);
next.clear();
}
return ans;
}
void DFS(TreeNode* root , int depth, vector<vector<int>>& ans){
if(root == NULL) return;
while(ans.size() <= depth) ans.push_back({});
DFS(root->left,depth+1, ans);
DFS(root->right,depth+1,ans);
ans.push_back(root->val);
}
};
optimized DFS
/**
* 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) {
// return BFS(root);
vector<vector<int>> ans;
if(!root) return ans;
DFS(root,0, ans);
return ans;
}
private:
void DFS(TreeNode* root , int depth, vector<vector<int>>& ans){
if(root != NULL) {
if(ans.size() > depth){
ans.push_back(root->val);
}else{
ans.push_back(vector <int>{root->val});
}
DFS(root->left, depth+1, ans);
DFS(root->right,depth+1, ans);
}
}
};
页:
[1]