Here is my AC C++ solution, use std::deque<TreeNode *>, any better?


  • 0
    class Solution
    {
    public:
        std::vector<std::vector<int> > levelOrder(TreeNode *root)
        {
            std::vector<std::vector<int> > result;
    		if (root == NULL)
    		{
    			return result;
    		}
    		std::deque<TreeNode *> wait_nodes;
    		wait_nodes.push_back(root);
    		wait_nodes.push_back(NULL);
    		std::vector<int> nodes_val;
    		while (wait_nodes.size() != 1)
    		{
    			root = wait_nodes.front();
    			wait_nodes.pop_front();
    			while (root != NULL)
    			{
    				nodes_val.push_back(root->val);
    				if (root->left != NULL)
    				{
    					wait_nodes.push_back(root->left);
    				}
    				if (root->right != NULL)
    				{
    					wait_nodes.push_back(root->right);
    				}
    				root = wait_nodes.front();
    				wait_nodes.pop_front();
    			}
    			result.push_back(nodes_val);
    			wait_nodes.push_back(NULL);
    			nodes_val.clear();
    		}
    		return result;
        }
    };

  • 0
    S
    This post is deleted!

Log in to reply
 

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