Open yankewei opened 2 years ago
简单的树遍历
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution {
private int $level = 0;
private int $sum = 0;
/**
* @param TreeNode $root
* @return Integer
*/
function deepestLeavesSum(TreeNode $root) {
$dfs = function (TreeNode $root, int $level) use (&$dfs): void {
if ($root->left === null && $root->right === null) {
if ($level > $this->level) {
$this->level = $level;
$this->sum = $root->val;
} else if ($level === $this->level) {
$this->sum += $root->val;
}
}
if ($root->left !== null) {
$dfs($root->left, $level+1);
}
if ($root->right !== null) {
$dfs($root->right, $level+1);
}
};
$dfs($root, 0);
return $this->sum;
}
}
给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和 。
示例 1:
示例 2:
提示:
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/deepest-leaves-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。