4ms c++ solution deque bfs


  • 0
    N
    if (nullptr == root)
    	return vector<vector<int>>();
    vector<vector<int>> result;
    deque<TreeNode *>que;
    que.push_back(root);
    int depth = 0;
    while (!que.empty())
    {
    	int len = que.size();
    	vector<int> temp;
    	for (int i = 0; i < len; ++i)
    	{
    		TreeNode *p = que.front();
    		que.pop_front();
    		if (depth % 2 == 0)
    			temp.push_back(p->val);
    		else
    			temp.insert(temp.begin(), p->val);
    		if (p->left)
    			que.push_back(p->left);
    		if (p->right)
    			que.push_back(p->right);
    	}
    	depth++;
    	result.push_back(temp);
    }
    return result;

Log in to reply
 

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