Leetcode PHP题解--D108 404. Sum of Left Leaves

D108 404. Sum of Left Leaves

题目链接

404. Sum of Left Leaves

题目分析

计算二叉树中所有左子节点的值之和。

思路

遍历二叉树。遍历左节点时传入标识。若遍历的当前的左右子树皆为空,且当前节点是左节点时,算入合内。

最终代码

val = $value; }
 * }
 */
class Solution {
    public $val = 0;
    /**
     * @param TreeNode $root
     * @return Integer
     */
    function sumOfLeftLeaves($root) {
        $this->preOrder($root,false);
        return $this->val;
    }
    
    function preOrder($root, $isLeft){
        if(!is_null($root->left)){
            $this->preOrder($root->left, true);
        }
        if(!is_null($root->right)){
            $this->preOrder($root->right, false);
        }
        if(is_null($root->left) && is_null($root->right) && $isLeft){
            $this->val += $root->val;
        }
    }
}

若觉得本文章对你有用,欢迎用爱发电资助。

你可能感兴趣的:(算法,leetcode,php)