My solution with Level Order Traval (none-recursion)


  • 0
    B
    struct TreeNodeWithSum {
            int sum;
            TreeNode *node;
            TreeNodeWithSum(TreeNode *x, int y): node(x), sum(y) {}
    };
    
    class Solution {
    public:
    
        int sumNumbers(TreeNode *root) {
            queue<TreeNodeWithSum> Q;
            int total = 0;
            if ( root == NULL )
                return 0;
            
            Q.push(TreeNodeWithSum(root,root->val));
            while(!Q.empty()) {
                TreeNodeWithSum temp = Q.front();
                Q.pop();
                if ( temp.node->left == NULL && temp.node->right == NULL ) {
                    total += temp.sum;
                }
                if ( temp.node->left != NULL ) {
                    Q.push(TreeNodeWithSum(temp.node->left,temp.sum*10+temp.node->left->val));
                }
                if ( temp.node->right != NULL ) {
                    Q.push(TreeNodeWithSum(temp.node->right,temp.sum*10+temp.node->right->val));
                }
                
            }
            return total;
        }
    };

Log in to reply
 

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