404. Sum of Left Leaves(C语言)

来源:互联网 发布:欧阳娜娜 知乎 编辑:程序博客网 时间:2024/06/03 19:10

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

Example:

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

我是看了答案才觉得其实明白了题意,答案也就出来了

求树里面,所有有左孩子,而左孩子没有孩子的这样的左孩子值的和


/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */int sumOfLeftLeaves(struct TreeNode* root) {    if(root==NULL){        return 0;    }    if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL){        return root->left->val+sumOfLeftLeaves(root->right);    }    return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);}


0 0
原创粉丝点击