257. 二叉树的所有路径
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
if(root==null) return ans;
dfs(root,"",ans);
return ans;
}
public void dfs(TreeNode root,String cur,List<String> ans)
{
if(root==null) return;
cur+=root.val;
if(root.left==null&&root.right==null)
ans.add(cur);
else
{
dfs(root.left,cur+"->",ans);
dfs(root.right,cur+"->",ans);
}
}
}
以及官方题解
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<String>();
constructPaths(root, "", paths);
return 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);
}
}
}
}
112. 路径总和
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null)
return false;
if(root.left==null&&root.right==null)
return (root.val==sum);
return hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum-root.val);
}
}
113. 路径总和 II
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
if(root==null) return ans;
if(root.left==null&&root.right==null&&root.val==sum)
{
temp.add(root.val);
ans.add(temp);
return ans;
}
List<List<Integer>> leftpath =pathSum(root.left,sum-root.val);
List<List<Integer>> rightpath = pathSum(root.right,sum-root.val);
for(List<Integer> list:leftpath)
{
list.add(0,root.val);
ans.add(list);
}
for(List<Integer> list:rightpath)
{
list.add(0,root.val);
ans.add(list);
}
return ans;
}
}