搜索
您的当前位置:首页正文

leetcode404:左叶子之和

来源:吉趣旅游网

思路

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

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表示它的子节点而不是点号

比较

因篇幅问题不能全部显示,请点此查看更多更全内容

Top