给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
图1 二叉树的所有路径
示例 1:
输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解一、递归求法,左右节点均为空时进行字符串拼接加入结果列表,不为空,继续递归左右节点进行字符串拼接后的参数变化。
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
String path = "";
dfs(root, path, res);
return res;
}
public void dfs(TreeNode root, String path, List<String> res) {
if (root == null) return;
if (root.left == null && root.right == null) {
res.add(path + root.val);
}
dfs(root.left, path + root.val + "->", res);
dfs(root.right, path + root.val + "->", res);
}
}
题解二、层序遍历直至遇到左右节点为空,进行拼接,不为空时,前面路径 + "->" + 左(右)节点值
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) return res;
Queue<Object> queue = new LinkedList<>();
queue.offer(root);
queue.offer("" + root.val);
while (!queue.isEmpty()) {
TreeNode node = (TreeNode) queue.poll();
String path = (String) queue.poll();
if (node.left == null && node.right == null) {
res.add(path);
}
if (node.left != null) {
queue.offer(node.left);
queue.offer(path + "->" + node.left.val);
}
if (node.right != null) {
queue.offer(node.right);
queue.offer(path + "->" + node.right.val);
}
}
return res;
}
}