给定一个二叉树,返回所有从根节点到叶子节点的路径。
示例:
第一次写出递归,记录一下
解法一:递归法
递归三步:
1.确定函数入参和返回值,入参为当前节点,和到当前节点的路径字符串,返回值为空即可
2.确定终止条件,到叶子节点的时候就可以把入参的路径字符串加到结果集合中
3.确定单层逻辑,递归当前节点的左右节点,拼接上节点值即可
class Solution {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if (root == null) {
return res;
}
String s = "" + root.val;
dfs(root,s);
return res;
}
public void dfs(TreeNode root, String s) {
if (root.right == null && root.left == null) {
res.add(s);
}
if (root.left != null) {
dfs(root.left,s + "->" + root.left.val);
}
if (root.right != null) {
dfs(root.right,s + "->" + root.right.val);
}
}
}
解法二:迭代法
先序遍历加入节点和路径,遍历左右节点时拼接节点值,判断一下是否叶子节点即可
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<Object> stack = new Stack<>();
stack.push(root);
String s = "" + root.val;
stack.push(s);
while (!stack.isEmpty()) {
String path = (String) stack.pop();
TreeNode node = (TreeNode) stack.pop();
if (node.right == null && node.left == null) {
res.add(path);
}
if (node.right != null) {
stack.push(node.right);
stack.push(path + "->" + node.right.val);
}
if (node.left != null) {
stack.push(node.left);
stack.push(path + "->" + node.left.val);
}
}
return res;
}