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

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


Vote Vote Cancel Collect Collect Cancel

<< 上一篇: Leetcode刷题之PHP解析(96. Unique Binary Search Trees)

>> 下一篇: Leetcode PHP题解--D109 122. Best Time to Buy and Sell Stock II