How about using the height of the binary tree?


  • 0
    B
    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> pointvec;
        vector<int> hashvec;
        vector<int> resTemp;
        vector< vector<int> > res;
        
        void treeHeight(TreeNode* root, int height){
        	if(root==NULL)
        		return;
        	else
        	{
        		treeHeight(root->left, height+1);
        		treeHeight(root->right, height+1);
        		pointvec.push_back(root->val);
        		hashvec.push_back(height);
        	}
        }
        
        vector< vector<int> > levelOrderBottom(TreeNode *root) {
            if(root==NULL)
        		return res;
        	else
        	{
            	int temp;
            	treeHeight(root,1);
            		
            	temp = hashvec[0];//temp为hashvec值中的最大
            	for (int i=1; i<hashvec.size(); i++)
            		if(hashvec[i]>temp)
            			temp = hashvec[i];
            
            	for(int i=temp;i>0;i--)
            	{
            	    resTemp.clear();
            		for (int j=0; j<hashvec.size(); j++)
            		{
            			if( i == hashvec[j] )
            			resTemp.push_back(pointvec[j]);
            		}
            		res.push_back(resTemp);
            	}
            	return res;
        	}
        }
        
    };

Log in to reply
 

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