LeetCode 404. Sum of Left Leaves (二叉树,递归)
来源:互联网 发布:985 211 区别知乎 编辑:程序博客网 时间:2024/05/17 04:39
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.输出二叉树左叶子节点的和。
思路:判断叶子节点的方法是,对于一个节点A,如果其左孩子和右孩子都不存在,则节点A是叶子节点。
进一步,判断左叶子节点:对于一个节点A的左孩子L,如果其左孩子和右孩子都不存在,则节点L是左叶子节点。
如果一个节点A的左孩子L是叶子节点,则返回节点L的值加上右子树的递归结果。
如果一个节点A的左孩子不是叶子节点(也就是左子树),则返回节点A的左右子树的递归结果之和。
/** * 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==NULL)return 0; if(root->left!=NULL && root->left->left==NULL && root->left->right==NULL)//root的左孩子是叶节点 return root->left->val + sumOfLeftLeaves(root->right); else return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); }};
阅读全文
0 0
- LeetCode 404. Sum of Left Leaves (二叉树,递归)
- 404.leetcode Sum of Left Leaves(easy)[二叉树 递归]
- LeetCode 404. Sum of Left Leaves(二叉树)
- 404. Sum of Left Leaves (二叉树)
- LeetCode 404. Sum of Left Leaves 递归终止条件
- LeetCode笔记:404. Sum of Left Leaves
- 【leetcode】404. Sum of Left Leaves【E】
- LeetCode—404. Sum of Left Leaves
- [LeetCode]404. Sum of Left Leaves
- Leetcode 404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- 404. Sum of Left Leaves - leetcode
- [LeetCode]--404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- [leetcode]404. Sum of Left Leaves
- LeetCode-404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- LeetCode 404. Sum of Left Leaves
- python学习之——常见错误汇总
- CaffeOnSpark安装和使用教程系列三:集群环境下使用CaffeOnSpark进行MNIST数据集的测试
- Java 生成二维码
- 格式化大于16TB的分区为ext4遇到的挫折
- 免费天气API,全国天气 JSON API接口,可以获取五天的天气预报
- LeetCode 404. Sum of Left Leaves (二叉树,递归)
- 使用jxl导出数据到excel中
- 高通Thermal Overview之thermal-engine
- ubuntu16.04 开wifi热点
- java 读取二维码
- oc之随机数
- 000044:使用break跳出循环
- 用not过滤返回的jQuery对象
- mysql grant提示无权限