上次编辑到这里,代码来自缓存 点击恢复默认模板
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
}
};
golang 解法, 执行用时: 0 ms, 内存消耗: 2.6 MB, 提交时间: 2021-07-02 11:49:28
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isLeafNode(node *TreeNode) bool {
return node.Left == nil && node.Right == nil
}
func dfs(node *TreeNode) (ans int) {
if node.Left != nil {
if isLeafNode(node.Left) {
ans += node.Left.Val
} else {
ans += dfs(node.Left)
}
}
if node.Right != nil && !isLeafNode(node.Right) {
ans += dfs(node.Right)
}
return
}
func sumOfLeftLeaves(root *TreeNode) int {
if root == nil {
return 0
}
return dfs(root)
}