zoukankan      html  css  js  c++  java
  • LeetCode 404. Sum of Left Leaves (C++)

    题目:

    Find the sum of all left leaves in a given binary tree.

    Example:

        3
       / 
      9  20
        /  
       15   7
    
    There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

    分析:

    给定一颗二叉树,求左叶子节点的和。

    重点在于如何判断左叶子节点,如果一个节点的left存在,且left的left和right都为空,那么我们就可以将这个节点的left->val记录下来。递归处理整颗树即可。

    程序:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int sumOfLeftLeaves(TreeNode* root) {
            if(!root)
                return 0;
            int sum = 0;
            if (root->left && !root->left->right && !root->left->left){
                sum = root->left->val;
            }
            return sum + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
        }
    };
  • 相关阅读:
    Shell脚本编程-02-----shell编程之条件语句
    ELK 简介
    Linux 下的网卡文件配置
    Tomcat 简介
    Docker 基本操作
    zabbix 介绍
    CentOS 上搭建 Kubernetes 集群
    Docker 简介
    yum 源的配置安装
    Docker 入门
  • 原文地址:https://www.cnblogs.com/silentteller/p/10705474.html
Copyright © 2011-2022 走看看