求二叉树的所有末级左节点的值的和
来源:互联网 发布:制衣打飞软件 编辑:程序博客网 时间:2024/06/07 07:38
题目:Sum of 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.
翻译:
这儿有2个末级左子节点,值分别为9和15,它们的和是24
答案:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int sumOfLeftLeaves(TreeNode root) { int sum = 0; if (root == null) return sum; TreeNode node = root.left; if (node != null) { if (node.left == null && node.right == null) sum += node.val; else sum += sumOfLeftLeaves(node); } sum += sumOfLeftLeaves(root.right); return sum; }}
算法说明:
利用递归,将末级左节点找到,并将值累加
0 0
- 求二叉树的所有末级左节点的值的和
- 求二叉树中的最大路径和,也就是求节点和节点之间的路径上所有节点的最大值
- 【算法题】求二叉树所有节点的左右子树的绝对值差的和
- 给定一个二叉树,节点值为0-9,从根节点到叶子结点组成一个数,求二叉树所有组成的数的和
- 求解二叉树所有节点的深度
- 二叉树求两个结点的父节点及一个结点的所有祖先结点
- 求二叉树节点的最大距离
- 求二叉树节点的最大距离
- 求二叉树节点的最大距离
- 求二叉树节点的最大距离
- 求二叉树节点的最大差值
- 求二叉树节点的最大距离
- 求二叉树的叶节点
- 求二叉树的叶子节点数目
- 求二叉树的节点数
- 求二叉树的下一个节点
- 求二叉树指定节点的深度
- 完全二叉树和满二叉树的区别+完全二叉树求节点问题
- 拆装机总结
- codevs1204 寻找子串位置
- HDOj 5918 Sequence I【KMP】
- 横竖屏切换SurfaceView 大小的调整
- Aho-Corasick 自动机
- 求二叉树的所有末级左节点的值的和
- mac下安装伪分布hadoop2.6.0和hbase1.0.1.1
- matplotlib中ion()和ioff()的使用
- KMeans——之我见
- PAT:1005. Spell It Right
- 【NOIP2010提高组T4】引水入城-搜索+DP
- Matlab中值滤波代码
- Autocad提示产品许可证错误无法激活的解决办法
- c语言显示比赛的结果