• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

leetcode404:左叶子:和

武飞扬头像
Coder_L2
帮助5

思路

左叶子的定义就是左节点不为空且没有左右孩子
可以采用递归来解
终止条件就是节点为空
单层递归条件是左节点不为空而且左右孩子的值为空

python语言

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: #终止条件
            return 0
        midValues = 0
        if root.left and not root.left.left and not root.left.right: #单层递归
            midValues = root.left.val
        return midValues self.sumOfLeftLeaves(root.left) self.sumOfLeftLeaves(root.right)

JS语言

var sumOfLeftLeaves = function(root) {
    if(root===null){
        return 0
    }
    let midvalues = 0
    if (root.left && root.left.left===null && root.left.right===null){
        midvalues = root.left.val
    }
    return midvalues sumOfLeftLeaves(root.left) sumOfLeftLeaves(root.right)
};

注意的是root节点为空是root===null

C语言

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(!root){
            return 0;
        }
            
        int midvalue=0;
        if(root->left && !root->left->left && !root->left->right){
            midvalue = root->left->val;
        }
        return midvalue sumOfLeftLeaves(root->left) sumOfLeftLeaves(root->right);
    }
};

注意在C语言中root->left表示它的子节点而不是点号

比较

学新通
其实思路明白了,语言只是实现的工具而已

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfibeif
系列文章
更多 icon
同类精品
更多 icon
继续加载