Leetcode 簡單二十八 路徑總和

路徑總和:

PHP:

28ms。遞歸。注意:葉子節點爲度爲0的節點。

/**
 * 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
     * @param Integer $sum
     * @return Boolean
     */
    function hasPathSum($root, $sum) {
        if($root == null){
            return false;
        }
        if($root->left == null && $root->right == null){
            return $sum - $root->val == 0;
        }
        return $this->hasPathSum($root->left,$sum - $root->val) || $this->hasPathSum($root->right,$sum - $root->val);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章