LetCode 404. Sum of Left Leaves (C++)
来源:互联网 发布:czur scanner软件 编辑:程序博客网 时间:2024/06/06 23:51
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.
思路:深度优先遍历,如果是左叶子节点则与left_sum相加。
/** * 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) { int left_sum = 0; dfs(root, left_sum); return left_sum; } int dfs(TreeNode* root, int & left_sum) { if (!root) return 0; if (root->left) left_sum += dfs(root->left, left_sum); if (root->right) dfs(root->right, left_sum); if(!(root->left) && !(root->right)) return root->val; return 0; }};
答案中更加简练的代码:
/** * 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) { int left_sum = 0; dfs(root, left_sum); return left_sum; } int dfs(TreeNode* root, int & left_sum) { if (!root) return 0; if (root->left) left_sum += dfs(root->left, left_sum); if (root->right) dfs(root->right, left_sum); if(!(root->left) && !(root->right)) return root->val; return 0; }};
阅读全文
0 0
- LetCode 404. Sum of Left Leaves (C++)
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves*
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- 404. Sum of Left Leaves
- Glide的使用
- 关于在IAR上用ST-Link下载出现“ST-Link, No MCU device found Session aborted! ”问题解决办法
- MySQL执行计划解读
- python方法生成txt标签文件代码
- 最简单的基于FFmpeg的推流器
- LetCode 404. Sum of Left Leaves (C++)
- 判空相关工具类
- python实现字典树的插入、查找功能并基于pickle模块持久化存储字典树
- 【0059】Axure RP 8汉化教程
- CAD图如何导入Visio
- poj1050最大字段和及其衍生
- Linux挂载windows共享目录
- 设备相关工具类
- __cplusplus 使用的一种场合