Binary Tree Level Order Traversal
原题链接Binary Tree Level Order Traversal
二叉树的逐层遍历,不过是要求每一层占用一个vector
递归即可,时刻记录当前处在第几层
/**
* 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;
levelOrder(root, res, 0);
return res;
}
private:
void levelOrder(TreeNode* root, vector<vector<int>>& res, int h)
{
if(!root) return;
if(h == res.size())
res.emplace_back(vector<int>());
levelOrder(root->left, res, h + 1);
levelOrder(root->right, res, h + 1);
res[h].emplace_back(root->val);
}
};
原题链接Binary Tree Level Order Traversal II
逐层遍历,要求顺序和上面相反
额,求完直接逆序即可
/**
* 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>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
levelOrder(root, res, 0);
std::reverse(res.begin(), res.end());
return res;
}
private:
void levelOrder(TreeNode* root, vector<vector<int>>& res, int h)
{
if(!root) return;
if(h == res.size())
res.emplace_back(vector<int>());
levelOrder(root->left, res, h + 1);
levelOrder(root->right, res, h + 1);
res[h].emplace_back(root->val);
}
};