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

本文介绍了一种解决二叉树中所有左叶子节点值之和的方法。通过递归遍历二叉树,并使用标记来区分左叶子节点,从而计算其总和。

D108 404. Sum of Left Leaves

题目链接

404. Sum of Left Leaves

题目分析

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

思路

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

最终代码

<?php
/**
 * 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 {
    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;
        }
    }
}

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

转载于:https://my.oschina.net/u/2246923/blog/3077765

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值