Sum of Left Leaves
来源:互联网 发布:三星s4可以用4g网络吗 编辑:程序博客网 时间:2024/04/30 13:23
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.思路:典型的dfs,preorder,也就是先把满足条件的写了,然后搜索左右两个子树。
满足条件的node要有两个属性:
1. 是最左点。
2. 而且最左点没有左右孩子,表明是leave。
/** * 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) { if(root == null) return 0; int[] res = {0}; collect(root, res); return res[0]; } public void collect(TreeNode root, int[] res){ if(root == null) return; if(root.left!=null){ if(root.left.left == null && root.left.right == null){ res[0] += root.left.val; } } collect(root.left, res); collect(root.right, res); }}
1 0
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- Sum of Left Leaves
- 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
- 开启mysql的远程访问权限
- 41个Web开发者必须收藏的JavaScript实用技巧
- 本地读取Json失败
- mysql关联查询怎么在查询软件中一下就能查询到所有的关联数据,修改的时候也方便,对比数据
- LINUX 删除 matlab
- Sum of Left Leaves
- 线性表数据结构解读(一)顺序存储结构ArrayList
- 跨平台原子操作
- 使用OrmLite数据库实现本地的账号登录,注册功能
- Scala Cookbook读书笔记 Chapter 4.Classes and Properties 第一部分
- MITA和MAUI框架
- phpstorm安装
- Qt之QTcpServer/QTcpSocket简单收发信息(1)
- js实现网页全屏切换(平滑过渡),鼠标滚动切换