My solution with Level Order and recursion


  • 0
    F

    recursion can make problems that requires from tail to head more brief

    class Solution {
    public:
    	typedef pair<int, TreeNode*> node;
    
    	void travel(vector<vector<int> >& res, queue<node>& q, int d) 
    	{
    		vector<int> v;
    		if(q.empty()) return;
    
    		while(!q.empty() && q.front().first == d)
    		{
    			node n = q.front();
    			v.push_back(n.second->val);
    
    			q.pop();
    			if(n.second->left) q.push(node(n.first + 1, n.second->left));
    			if(n.second->right) q.push(node(n.first + 1, n.second->right));
    		}
    		travel(res, q, d + 1);
    
    		res.push_back(v);
    	}
    	vector<vector<int> > levelOrderBottom(TreeNode *root) 
    	{
    		vector<vector<int> > res;
    		if(!root) return res;
    		
    		queue<node> q;
    		q.push(node(1, root));
    		
    		travel(res, q, 1);
    		return res;
    	}
    };

Log in to reply
 

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