Binary Tree Paths (E)
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
题意
打印一棵树从根结点到叶结点的所有路径。
思路
简单的DFS处理即可。
代码实现
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
if (root != null) {
dfs(root, ans, "");
}
return ans;
}
private void dfs(TreeNode x, List<String> ans, String s) {
s += s.equals("") ? x.val : "->" + x.val;
if (x.left != null) {
dfs(x.left, ans, s);
}
if (x.right != null) {
dfs(x.right, ans, s);
}
if (x.left == null && x.right == null) {
ans.add(s);
}
}
}
本文介绍了一种使用深度优先搜索(DFS)策略来解决二叉树所有根到叶子节点路径的问题。通过递归地遍历树的左右子节点,并在到达叶子节点时收集路径,实现了对所有路径的有效获取。

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



