首頁  >  文章  >  後端開發  >  PHP如何計算二元樹坡度

PHP如何計算二元樹坡度

醉折花枝作酒筹
醉折花枝作酒筹轉載
2021-07-09 15:21:521453瀏覽

一個樹某結點的坡度就是該結點左子樹的結點總和和右子樹結點總和的差的絕對值。今天我們就來聊聊計算二元樹坡度的方法,有需要的可以參考參考。

PHP如何計算二元樹坡度

給定一個二元樹,計算整個樹的坡度。

一個樹的節點的坡度定義即為,該節點左子樹的結點和和右子樹結點總和的差的絕對值。空結點的坡度是0。

整個樹的坡度就是其所有節點的坡度總和。

範例:

输入:
         1
       /   \
      2     3
输出:1
解释:
结点 2 的坡度: 0
结点 3 的坡度: 0
结点 1 的坡度: |2-3| = 1
树的坡度 : 0 + 0 + 1 = 1

解題想法

#遞迴遍歷二元樹,累加 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;
    }
}

推薦學習:php影片教學

#

以上是PHP如何計算二元樹坡度的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:hxd.life。如有侵權,請聯絡admin@php.cn刪除