Advertisement
Guest User

Untitled

a guest
May 6th, 2020
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const pathSum = (root, sum) => {
  2.     if(!root) return 0;
  3.    
  4.     let leafCountSet = new Set();
  5.     let pathsSet = new Set();
  6.    
  7.     const checkSum = (valSeqs, pathSeqs, sum) => {
  8.         const vals = valSeqs.slice(0, valSeqs.length - 1).split(',');
  9.         const paths = pathSeqs.slice(0, pathSeqs.length - 1).split(',');
  10.         const sums = [];
  11.         const pathsStrs = [];
  12.        
  13.         vals.forEach( (val, key) => {
  14.             for (let i = 0; i <= key; i++) {
  15.                 if(typeof(sums[i]) === 'undefined') {
  16.                     sums[i] = parseInt(val, 10);  
  17.                 } else {
  18.                     sums[i] += parseInt(val, 10);
  19.                 }
  20.                
  21.                
  22.                 if(sums[i] === sum) {
  23.                     // console.log('df');
  24.                     const pathStr = paths.slice(i, key).join('-');
  25.                     const sumsStr = sums.join('-');
  26.                     pathsStrs.push(pathStr + '-' + sumsStr);
  27.                 }
  28.             }
  29.         })
  30.        
  31.         // console.log('vals', valSeqs);
  32.         // console.log('pathSeqs', pathSeqs);
  33.        
  34.         return pathsStrs;
  35.     }
  36.    
  37.     const recursivePath = (root, sum, valSeqs = '', pathSeqs='', key='') => {
  38.        
  39.         if(root == null) {
  40.             const sumId = checkSum(valSeqs, pathSeqs, sum);
  41.             if(typeof(sumId) !== 'undefined') {
  42.                 sumId.forEach( path => leafCountSet.add(path))
  43.             }
  44.             // console.log('valSeqs', valSeqs);
  45.             pathsSet.add(valSeqs);
  46.             return;
  47.         }
  48.        
  49.         if(key) pathSeqs += key + ',';
  50.        
  51.         if(typeof(root.val) !== 'undefined') {
  52.              valSeqs += root.val + ',';
  53.         }
  54.        
  55.         recursivePath(root.right, sum, valSeqs, pathSeqs, 'right');
  56.         recursivePath(root.left, sum, valSeqs, pathSeqs, 'left');
  57.     }
  58.    
  59.     recursivePath(root, sum);
  60.     console.log(leafCountSet);
  61.     // console.log('-----------');
  62.     console.log('valSeqs', pathsSet);
  63.     return leafCountSet.size;
  64. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement