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

D108 404. Sum of Left Leaves

題目連接

404. Sum of Left Leavesphp

題目分析

計算二叉樹中全部左子節點的值之和。node

思路

遍歷二叉樹。遍歷左節點時傳入標識。若遍歷的當前的左右子樹皆爲空,且當前節點是左節點時,算入合內。this

最終代碼

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

若以爲本文章對你有用,歡迎用愛發電資助。.net

相關文章
相關標籤/搜索