设为首页 加入收藏

TOP

404. Sum of Left Leaves 解题记录
2018-10-21 20:08:34 】 浏览:87
Tags:404. Sum Left Leaves 解题 记录

题目描述:

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

例子:

 

    3
   / \
  9  20
    /  \
   15   7

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

 

解题思路:

用递推对二叉树进行遍历,判断是否为末枝的左子叶,然后将所有的末枝的左子叶相加(不要忘了考虑空指针的情况)

代码:

 

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 int sumOfLeftLeaves(struct TreeNode* root) {
10     if (!root)
11     //输入为空指针时
12     {
13         return 0;
14     }
15     int leftLeavesSum = 0;
16     if (root->left)
17     {
18         if (!root->left->left && !root->left->right)
19         //结束的条件也就是末枝的左子叶时
20         {
21             leftLeavesSum += root->left->val;
22         }
23         else
24         {
25                 leftLeavesSum += sumOfLeftLeaves(root->left);
26             }
27         }
28     if (root->right)
29         {
30             leftLeavesSum += sumOfLeftLeaves(root->right);
31         }
32     return leftLeavesSum;
33 }

 

解题收获:

对于C语言链表的使用还是有些不够熟练,还需要多加练习。

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇[编程] C语言循环结构计算π的值 下一篇C语言中数组与指针的关系

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目