二叉樹路徑總和

wifi發表於2020-05-13

給定一個二叉樹和一個目標和,判斷該樹中是否存在根節點到葉子節點的路徑,這條路徑上所有節點值相加等於目標和。

說明: 葉子節點是指沒有子節點的節點。

TreeNode.php

<?php
require 'TreeNode.php';

use Tree\TreeNode;

class Sum
{
    public function Recursive(?TreeNode $root, int $sum): bool
    {
        if (null == $root) {
            return false;
        }

        $sum -= $root->val;

        if ((null == $root->left) && (null == $root->right)) {
            return 0 == $sum;
        }

        return $this->Recursive($root->left, $sum) || $this->Recursive($root->right, $sum);
    }

    public function Interation(TreeNode $root, int $sum): bool
    {
        $nodeStack = [];
        $sumStack  = [];

        array_push($nodeStack, $root);
        array_push($sumStack, $sum - $root->val);

        while (boolval($nodeStack)) {
            $node    = array_pop($nodeStack);
            $currSum = array_pop($sumStack);

            if ((null == $node->right) && (null == $node->left) && (0 == $currSum)) {
                return true;
            }

            if (null != $node->right) {
                array_push($nodeStack, $node->right);
                array_push($sumStack, $currSum - $node->right->val);
            }

            if (null != $node->left) {
                array_push($nodeStack, $node->left);
                array_push($sumStack, $currSum - $node->left->val);
            }
        }

        return false;
    }
}

$t = new Sum();

var_dump($t->Interation($first, 6));
var_dump($t->Recursive($first, 5));
bool(true)
bool(false)

[Process exited 0]
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章