计算二叉树中全部左子节点的值之和。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