leecode每日一题01- Binary Tree Level Order Traversal [Medium]
程序员文章站
2022-07-12 12:02:57
...
关于二叉树的遍历查找。
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) {
vector<vector<int>>* res = new vector<vector<int>>();
levelHelper(res,root,0);
return *res;
}
//采用DFS的方法求解
void levelHelper(vector<vector<int>>* res,TreeNode* root,int level)
{
if(root == NULL) return;
if(level >= res->size())
{
res->push_back(vector<int>());
}
// cout<<"root_val="<<root->val<<" level="<<level<<endl;
res->at(level).push_back(root->val);
levelHelper(res,root->left,level+1);
levelHelper(res,root->right,level+1);
}
};
PS:本文摘自网络资源,仅供个人学习记录参考使用,同时与大家分享。
上一篇: 101.对称二叉树(通过)Python
下一篇: 递归求x的n次幂(C语言)