原题链接:https://leetcode-cn.com/problems/sum-of-left-leaves/

思路:
递归,dfs
左叶子节点:是父亲节点的左孩子,左节点和右节点都是null
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null) {
return 0;
}
if (root.left != null && root.left.left == null && root.left.right == null) {
// 左叶子节点 + root的右孩子对应的sumOfLeftLeaves
return root.left.val + sumOfLeftLeaves(root.right);
}
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}
}
这是一个关于二叉树的算法问题,目标是计算所有左叶子节点的值之和。解决方案使用了深度优先搜索(DFS)策略,通过递归遍历树的节点。当遇到非空节点时,如果该节点是左叶子节点(即它的左子节点存在且没有左右子节点),则将其值加入到总和中,然后继续遍历右子树。否则,继续递归遍历左子树和右子树。
497

被折叠的 条评论
为什么被折叠?



