layout: posttitle: PHP 计算二叉树坡度
subtitle: PHP 计算二叉树坡度
date: 2020-07-08
author: he xiaodong
header-img: img/default-post-bg.jpg
catalog: true
tags:
- Go
- PHP
- LeetCode
- 二叉树坡度

二叉树的坡度

给定一个二叉树,计算整个树的坡度。

一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。

整个树的坡度就是其所有节点的坡度之和。

示例:

  1. 输入:
  2. 1
  3. / \
  4. 2 3
  5. 输出:1
  6. 解释:
  7. 结点 2 的坡度: 0
  8. 结点 3 的坡度: 0
  9. 结点 1 的坡度: |2-3| = 1
  10. 树的坡度 : 0 + 0 + 1 = 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-tilt

解题思路

递归遍历二叉树,累加 abs($left - $right) 的值,每次返回左右节点和当前节点的和,用于下一次坡度计算。

php 代码

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($value) { $this->val = $value; }
  8. * }
  9. */
  10. class Solution {
  11. /**
  12. * @param TreeNode $root
  13. * @return Integer
  14. */
  15. private $total = 0;
  16. function findTilt($root) {
  17. $this->traverse($root);
  18. return $this->total;
  19. }
  20. function traverse($root) {
  21. if($root == null) {
  22. return 0;
  23. }
  24. $left = $this->traverse($root->left);
  25. $right = $this->traverse($root->right);
  26. $this->total += abs($left - $right);
  27. return $left + $right + $root->val;
  28. }
  29. }

最后恰饭 阿里云全系列产品/短信包特惠购买 中小企业上云最佳选择 阿里云内部优惠券