C++ iterative solution


  • 0
    F
    TreeNode* traverse = root;
    int sum = 0;
    stack < TreeNode* > stacky;
    while ( 1 ) {
    	if ( traverse ) {
    		stacky.push( traverse );
    		traverse = traverse->right;
    	} else {
    		if ( !stacky.empty() ) {
    			traverse = stacky.top(); stacky.pop();
    			traverse->val += sum;
    			sum = traverse->val;
    			traverse = traverse->left;
    		} else {
    			break;
    		}
    	}
    }
    return root;

Log in to reply
 

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