1. 程式人生 > >Leetcode PHP題解--D108 404. Sum of Left Leaves

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

若覺得本文章對你有用,歡迎用