Problem:
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]
]
Answer:
使用递归,并维护一个深度
> res;
void dfs(TreeNode* t,int d){
if(t==NULL) return;
if(res.size()<=d) res.push_back(vector());
res[d].push_back(t->val);
if(t->left) dfs(t->left,d+1);
if(t->right) dfs(t->right,d+1);
return;
}
vector> levelOrder(TreeNode* root) {
if(root==NULL) return res;
dfs(root,0);
return res;
}
};
原文链接:https://www.f2er.com/note/422440.html