链式求和

假如有如下图所示的数据结构:

转换成为 js 代码为如下构造:

const chainNode = {
  value: 1,
  left: {
    value: 2,
    left: {
      value: 4,
      left: {
        value: 7
      }
    }
  },
  right: {
    value: 3,
    left: {
      value: 5,
      left: {
        value: 8
      }
    },
    right: {
      value: 6,
      left: {
        value: 9
      },
      right: {
        value: 10
      }
    }
  }
}

求所有链条数字之和,如下所示:
1 + 2 + 4 + 7 +
1 + 3 + 5 + 8 +
1 + 3 + 6 + 9 +
1 + 3 + 6 + 10

解题思路:
1、如上图所示共有 4 个末端节点别离为 7 、8 、9 、10
2、求末端节点以及其父节点的总和 currentChainSum 并叠加到最终总和 total 里

function getChainSum(chainNode) {
      // 总和
      let total = 0 
      // 叠加计算器
      const accumulator = (chainNode, prevChainSum = 0) => {
        const {value, left, right} = chainNode
        // 以后节点的值 + 以后节点的所有父节点之和
        const currentChainSum = value + prevChainSum
        // 如果有 left 节点则持续叠加
        left && accumulator(left, currentChainSum)
        // 如果有 right 节点则持续叠加
        right && accumulator(right, currentChainSum)
        // 当节点达到末端时叠加总和
        if (!left && !right) {
          total += currentChainSum
        }
      }
      accumulator(chainNode)
      return total
    }

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理