Leetcode - Binary Tree Paths
来源:互联网 发布:国内衬衫品牌 知乎 编辑:程序博客网 时间:2024/06/10 02:38
Question
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
Java Code
public List<String> binaryTreePaths(TreeNode root) { String path = new String(); List<String> pathList = new LinkedList<String>(); if(root == null) return pathList;//空树则返回空的pathList(空List不等同于null) recordPath(root, path, pathList); return pathList;}//DFS遍历二叉树,并一直传递当前的路径path和所有的路径pathListpublic void recordPath(TreeNode root, String path, List<String> pathList) { //如果已经到达叶子节点,在pathList中记录该条路径,结束该条路径的遍历 if(root.left == null && root.right == null) { pathList.add(path + root.val); return; } //如果存在左子节点,在当前路径中加入当前节点,并继续遍历左子树 if(root.right != null) recordPath(root.right, path + root.val + "->", pathList); //如果存在右子节点,在当前路径中加入当前节点,并继续遍历右子树 if(root.left != null) recordPath(root.left, path + root.val + "->", pathList);}
说明
- 代码中递归函数recordPath的特点是,每次递归深入时即遍历二叉树下一层节点时,将当前节点添加到path字符串中,从而path中按顺序记录了当前节点的所有父辈节点。由于DFS遍历时随时可能遇到叶子节点即到达某条路径的端点,此时我们需要保存path,这无法通过将path作为recordPath的返回值来实现,因为这样会在每一层递归退出时都返回path,而我们只需要保存达到路径端点时的path,所以必须要给递归函数recordPath再传递一个List变量,用于保存每一个完整的path,并且List变量传参时传递的是自身的引用而不是自身的一个副本。
0 0
- Leetcode: Binary Tree Paths
- [LeetCode] Binary Tree Paths
- [Leetcode]Binary Tree Paths
- leetcode:Binary Tree Paths
- [leetcode] Binary Tree Paths
- Leetcode: Binary Tree Paths
- LeetCode:Binary Tree Paths
- leetcode Binary Tree Paths
- leetcode Binary Tree Paths
- LeetCode:Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode Binary Tree Paths
- LeetCode || Binary Tree Paths
- *LeetCode-Binary Tree Paths
- Binary Tree Paths -- leetcode
- LeetCode---Binary Tree Paths
- leetcode-Binary Tree Paths
- 网络仿真工具TOTEM之——IP路由功能
- busybox_httpd, http, CGI
- Android Studio 自定义View命名空间报错的解决方法
- Spring 实现初始化和销毁bean之前进行的操作的方法
- json解析的用法,用框架的用法简单介绍:
- Leetcode - Binary Tree Paths
- java 的Exception和Error
- Oracle数据库和SQLServer数据库中创建DB-Link语法
- 解决 Express Command not found
- java序列化的作用和反序列化
- 浅谈Android之webView及交互
- c++的多态
- c++ 模版template —— c++(复习七)
- Log4j使用教程