Brute Force Accepted. Self explanatory.


  • 0
    S

    Creating a tree and find the sum of all paths the traditional way.

    class Solution {
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
    private:
        int paths(TreeNode* root, int sum){
            if(!root){
                return 0;
            }
            sum += root->val;
            if(root->left == NULL && root->right == NULL){
                return sum;
            }
            return paths(root->left, sum)+paths(root->right, sum);
        }
    public:
        int pathSum(vector<int>& nums) {
            TreeNode* root = new TreeNode(0);
            
            int n = nums.size();
            for(int i=0; i<n; i++){
                int t = nums[i];
                int value = t%10;
                t/=10;
                int pos = t%10;
                t/=10;
                int depth = t%10;
                TreeNode* temp = new TreeNode(value);
                if(depth == 1){
                    root->val = value;
                }
                if(depth == 2){
                    (pos == 1) ? root->left = temp : root->right = temp;
                }
                if(depth == 3){
                    if(pos == 1){
                        root->left->left = temp;
                    }else if(pos == 2){
                        root->left->right = temp;
                    }else if(pos == 3){
                        root->right->left = temp;
                    }else{
                        root->right->right = temp;
                    }
                }
                if(depth == 4){
                    if(pos == 1){
                        root->left->left->left = temp;
                    }else if(pos == 2){
                        root->left->left->right = temp;
                    }else if(pos == 3){
                        root->left->right->left = temp;
                    }else if(pos == 4){
                        root->left->right->right = temp;
                    }else if(pos == 5){
                        root->right->left->left = temp;
                    }else if(pos == 6){
                        root->right->left->right = temp;
                    }else if(pos == 7){
                        root->right->right->left = temp;
                    }else{
                        root->right->right->right = temp;
                    }
                }
            }
            
            int sum = paths(root, 0);
            return sum;
        }
    };
    

Log in to reply
 

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