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));
    }
}
posted @ 2021-07-15 23:35  吴丹阳-V  阅读(11)  评论(0编辑  收藏  举报