| java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.youkuaiyun.com/grd_java/article/details/123063846 |
|---|
| 解题思路 |
|---|
- 直接使用深度优先遍历
- 每次都将结点记录到路径字符串中
- 如果当前结点是叶子结点,说明一条路径遍历完成,直接添加到链表中
- 如果当前结点不是叶子结点,说明这条路径没有遍历完成,则添加->符号后,继续深度优先遍历
| 代码 |
|---|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();//保存答案
constructPaths(root, "", paths);
return paths;
}
/**
path保存路径
paths 保存答案
*/
public void constructPaths(TreeNode root, String path, List<String> paths) {
if (root != null) {//如果当前结点不为空
StringBuffer pathSB = new StringBuffer(path);//保存路径
pathSB.append(Integer.toString(root.val));//将当前结点保存
if (root.left == null && root.right == null) { // 如果当前节点是叶子节点,说明找到一条路径
paths.add(pathSB.toString()); // 把路径加入到答案中
} else {//如果当前依然不是叶子结点,说明后面还有,那么需要一个->符号
pathSB.append("->"); // 当前节点不是叶子节点,继续递归遍历
constructPaths(root.left, pathSB.toString(), paths);//左子树
constructPaths(root.right, pathSB.toString(), paths);//右子树
}
}
}
}


359

被折叠的 条评论
为什么被折叠?



