Non-recursive C++ solution


  • 0
    M
    #include <deque>
    
    class Solution {
    public:
        std::vector<std::vector<int> > levelOrder(TreeNode* root) {
            std::vector<std::vector<int> > r;
            std::deque<TreeNode*> level;
            if (root) {
                level.push_back(root);
            }
            while (!level.empty()) {
                r.push_back(std::vector<int>());
                int n = level.size();
                r.back().reserve(n);
                for (int i = 0; i < n; ++i) {
                    r.back().push_back(level.front()->val);
                    if (level.front()->left) {
                        level.push_back(level.front()->left);
                    }
                    if (level.front()->right) {
                        level.push_back(level.front()->right);
                    }
                    level.pop_front();
                }
            }
            return r;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.