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