[LeetCode]404. Sum of Left Leaves(叶子结点的和)

404. Sum of Left Leaves

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.

思路:
用DFS遍历,递归。DFS定义

代码1:

C++

#include <iostream>
using namespace std;
class Solution {//求左叶子节点的和
public:
    // Definition for a binary tree node.
    struct TreeNode {
       int val;
       TreeNode *left;
       TreeNode *right;
       TreeNode(int x) : val(x), left(NULL), right(NULL) {}
   };
    int sumOfLeftLeaves(TreeNode* root) {
        if(root == nullptr)
            return 0;
        //判断节点是否有左孩子
        if(root->left){//节点有左孩子节点
            if(root->left->left == nullptr && root->left->right == nullptr)//节点左孩子是叶子节点
                return root->left->val + sumOfLeftLeaves(root->right);
            else//节点左孩子有子节点
                return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
        }
        else//节点没有左孩子节点
            return sumOfLeftLeaves(root->right);
    }
};
int main()
{
    if(1)
        cout << "Hello world!" << endl;
    return 0;
}

代码2:

int sumOfLeftLeaves1(TreeNode* root) {
        //如果root为空,返回0
        if(root == nullptr)
            return 0;
        //判断节点是否为左叶子节点
        //如果左子树即为左叶子节点,则返回左叶子节点的val值+sumOfLeftLeaves(右子树)的值
        if(root->left!=nullptr && root->left->left==nullptr && root->left->right==nullptr)
            return root->left->val+sumOfLeftLeaves(root->right);
        else
        //否则返回递归调用sumOfLeftLeaves(左子树)+sumOfLeftLeaves(右子树)的值
            return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
    }

代码3:

//先判断是否是叶子节点,然后是判断是否是左孩子,叶子节点很容易判断,左孩子需要加一个标记。
    int sumOfLeftLeaves2(TreeNode* root) {
        int res = 0;
        DFS(root, 0, res);//0 false   1 true
        return res;
    }
    void DFS(TreeNode* root, bool f, int&s){//bool 判断是否为左孩子 0 false   1 true
        if(!root)//节点为空
            return;
        if(!root->left && !root->right){//节点左右孩子为空(叶子节点)
            if(f)
                s += root->val;
             return;
        }
        if(root->left)
            DFS(root->left, 1, s);
        if(root->right)
            DFS(root->right, 0, s);
    }

注意:

  1. 是所有左叶子节点的和,而不是左孩子节点的和
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值