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 3输出:1解释:结点 2 的坡度: 0结点 3 的坡度: 0结点 1 的坡度: |2-3| = 1树的坡度 : 0 + 0 + 1 = 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-tilt
解题思路
递归遍历二叉树,累加 abs($left - $right) 的值,每次返回左右节点和当前节点的和,用于下一次坡度计算。
php 代码
/*** Definition for a binary tree node.* class TreeNode {* public $val = null;* public $left = null;* public $right = null;* function __construct($value) { $this->val = $value; }* }*/class Solution {/*** @param TreeNode $root* @return Integer*/private $total = 0;function findTilt($root) {$this->traverse($root);return $this->total;}function traverse($root) {if($root == null) {return 0;}$left = $this->traverse($root->left);$right = $this->traverse($root->right);$this->total += abs($left - $right);return $left + $right + $root->val;}}
