LeetCode257. Binary Tree Paths
来源:互联网 发布:微软sql 编辑:程序博客网 时间:2024/06/09 17:06
257. Binary Tree Paths
1 / \2 3 \ 5
["1->2->5", "1->3"]
题意:
给出一个二叉树,返回所有根节点到叶子的路径
public class LeetCode257 { public List<String> binaryTreePaths(TreeNode root) { List<String> path = new ArrayList<>(); if(root == null) return path; String onepath = ""; paths(root, onepath, path); return path; } public static void paths(TreeNode root, String curPath, List<String> path){ curPath = curPath + root.val ; if(root.left == null && root.right == null){ // 到达叶子节点 path.add(curPath); } curPath = curPath + "->"; if(root.left != null){ paths(root.left, curPath, path); } if(root.right != null){ paths(root.right, curPath, path); } }}
129. Sum Root to Leaf Numbers
题意:
找到所有根到叶子的数字和
例如:
1 / \2 3
1->2 代表12
1->3 代表13
所有根到叶子的和为:12+13=25
解题思路:
思路1:和上题类似,先求出所有路径,推进一步乘以10,求出所有数字,然后相加。
思路2:递归相加
public class LeetCode129 { /* public int sumNumbers(TreeNode root) { List<Integer> path = new ArrayList<>(); int res = 0; if(root == null) return res; paths(root, 0, path); for(Integer tmp:path){ res = res + tmp; System.out.println(tmp); } return res; } public static void paths(TreeNode root, int curPath, List<Integer> path){ curPath = curPath + root.val ; if(root.left == null && root.right == null){ path.add(curPath); } curPath = curPath * 10; if(root.left != null){ paths(root.left, curPath, path); } if(root.right != null){ paths(root.right, curPath, path); } } */ public int sumNumbers(TreeNode root) { return dfs(root, 0); } public int dfs(TreeNode root, int sum) { if(root == null) return 0; if(root.left == null && root.right == null) return root.val + sum * 10; return dfs(root.left, root.val + sum * 10) + dfs(root.right, root.val + sum * 10); } }
0 0
- [LeetCode257] Binary Tree Paths
- leetcode257 Binary Tree Paths
- leetcode257---Binary Tree Paths
- LeetCode257:Binary Tree Paths
- LeetCode257. Binary Tree Paths
- leetcode257 Binary Tree Paths
- leetcode257. Binary Tree Paths
- LeetCode257——Binary Tree Paths
- LeetCode257. Binary Tree Paths(dfs)
- Binary Tree Paths
- Leetcode: Binary Tree Paths
- [LeetCode] Binary Tree Paths
- [Leetcode]Binary Tree Paths
- leetcode:Binary Tree Paths
- Binary Tree Paths
- [leetcode] Binary Tree Paths
- 257 Binary Tree Paths
- Binary Tree Paths
- Android 炫酷插件
- MSSQL存储过程中执行动态Sql语句
- tp5查询
- MySql多表分页
- 隐式Intent匹配规则
- LeetCode257. Binary Tree Paths
- java集合框架
- window服务器通过sftp从linux下载文件,并ftp上传到window服务器
- 仿射变换的通俗解释
- liunx系统禁止usb存储设备使用
- android studio failed to open zip file .Android Studio Error:Connection timed out: connect.
- AM5728调试经历
- 限制p元素之显示2行文字,同时出现省略号。
- boost::future<T>::then & Autobahn C++ 内存占用高问题分析: