Sum root to leaf numbers

Approach 1:

class Solution {
public:
    int sumNumbers(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int sum = 0;
        int ret_sum = 0;
        if (root == NULL)
            return sum;
        stack<TreeNode *> stack;
        stack.push(root);
        while (!stack.empty()) {
            if (root != NULL) {
                if (root->left != NULL) {
                    root->left->val += root->val * 10;
                    stack.push(root->left);
                }
                root = root->left;
            } else {
                root = stack.top();
                stack.pop();
                if (root->right == NULL && root->left == NULL) {
                    ret_sum += root -> val;
                } else if (root->right != NULL) {
                    stack.push(root->right);
                    root -> right -> val += root->val * 10;
                }
                root = root -> right;
            }
        }
        return ret_sum;
    }
};


Approach 2:
class Solution {
public:
    int sumNumbers(TreeNode *root) {
        int sum = 0;
        if(root) {
            stack<TreeNode *> stk;
            stk.push(root);
            while(!stk.empty()) {
                TreeNode *node = stk.top();
                stk.pop();
                if(!node->left && !node->right) sum+=node->val;
                if(node->right) {
                    node->right->val += node->val*10;
                    stk.push(node->right);
                }
                if(node->left) {
                    node->left->val += node->val*10;
                    stk.push(node->left);
                }
            }
        }
        return sum;
    }
};

No comments:

Post a Comment