输入: { 1,2 }
返回值:[[1], [2]]
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > levelOrder(TreeNode* root) {
// write code here
vector<vector<int>> a;
cengorder(root, 0, a);
return res;
}
void cengorder(TreeNode* root, int depth, vector<vector<int>> &a) //与前序、中序、后序比较多了参数depth
{
if (!root)
return;
if (a.size() == depth)
a.push_back(vector<int>());
a[depth].push_back(root->val);
cengorder(root->left, depth + 1, a);
cengorder(root->right, depth + 1, a);
}
};
二叉树遍历(层次)递归法
最新推荐文章于 2023-07-06 15:00:38 发布