leetcode-404. 左叶子之和
题目
https://leetcode-cn.com/problems/sum-of-left-leaves/
解法
树的遍历,so easy
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution {
private $sum = 0;
/**
* @param TreeNode $root
* @return Integer
*/
function sumOfLeftLeaves($root, $left = false) {
if (empty($root)) {
return $this->sum;
}
if ($left && $this->isLeaf($root)) {
$this->sum += $root->val;
return $this->sum;
}
$this->sumOfLeftLeaves($root->left, true);
$this->sumOfLeftLeaves($root->right, false);
return $this->sum;
}
function isLeaf($root) {
return (empty($root->left) && empty($root->right));
}
}
本文来自博客园,作者:吴丹阳-V,转载请注明原文链接:https://www.cnblogs.com/wudanyang/p/15018089.html