路径总和:

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);
    }
}

 

相关文章:

  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
  • 2021-12-06
  • 2021-04-08
  • 2021-10-28
  • 2021-09-21
  • 2021-05-12
猜你喜欢
  • 2022-01-15
  • 2021-08-27
  • 2021-06-12
  • 2021-05-12
  • 2021-06-07
  • 2021-12-18
  • 2022-01-01
相关资源
相似解决方案