Advertisement
vit134

Сумма узлов дерева (рекурсия)

Oct 25th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.     Найти сумму значений всех узлов дерева
  3. */
  4.  
  5. var tree = {
  6.     valueNode: 3,
  7.     next: [
  8.         {
  9.             valueNode: 1,
  10.             next: null
  11.         },
  12.         {
  13.             valueNode: 3,
  14.             next: null
  15.         },
  16.         {
  17.             valueNode: 2,
  18.             next: null
  19.         },
  20.         {
  21.             valueNode: 2,
  22.             next: [
  23.                 {
  24.                     valueNode: 1,
  25.                     next: null
  26.                 },
  27.                 {
  28.                     valueNode: 5,
  29.                     next: null
  30.                 }
  31.             ]
  32.         }
  33.     ]
  34. };
  35.  
  36. function walkTree(tree) {
  37.     let sum = 0;
  38.  
  39.     function Walk(node) {
  40.         sum += node.valueNode;
  41.         if (node.next) {
  42.             node.next.forEach(el => {
  43.                 Walk(el);
  44.             });
  45.         }
  46.  
  47.         return sum;
  48.     }
  49.  
  50.     return Walk(tree);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement