阅读 105

LeetCode 102 Binary Tree Level Order Traversal

LeetCode 102 Binary Tree Level Order Traversal

思路

递归

递归很好写,用一个变量记录当前遍历到第几层即可。任意顺序遍历均可。

迭代

正如前一题总结的那样,一层一层的考虑树,则使用队列。

代码

递归

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        map<int, vector<int>> mp;
        
        preorder(root, mp, 0);
        
        vector<vector<int>> rs;
        for (const auto &i : mp) {
            rs.emplace_back(i.second);
        }
        
        return rs;
    }
    
    void preorder(TreeNode *root, map<int, vector<int>> &mp, int level) {
        if (!root) return ;
        
        mp[level].push_back(root->val);
        preorder(root->left, mp, level+1);
        preorder(root->right, mp, level+1);
    }
};
复制代码

迭代

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> qu;
        vector<vector<int>> rs;
        qu.push(root);
        int n = qu.size();
        
        while (!qu.empty()) {
            vector<int> level;
            while (n--) {
                root = qu.front();
                qu.pop();
                if (root) {
                    level.push_back(root->val);
                    qu.push(root->left);
                    qu.push(root->right);
                }
            }
            
            if (!level.empty())
                rs.push_back(level);
            n = qu.size();
        }
        
        return rs;
    }
};
复制代码
文章分类
阅读
文章标签