路径总和
思路:递归
使用递归遍历整棵树
代码如下:
/**
* 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 hasPathSum(root.left,sum - root.val) || hasPathSum(root.right,sum - root.val);
}
else if(root.left != null){
return hasPathSum(root.left,sum - root.val);
}
else if(root.right != null){
return hasPathSum(root.right,sum - root.val);
}
else{
return root.val == sum;
}
}
}
时间复杂度:遍历了二叉树的每个节点,时间复杂度为O(N)
额外空间复杂度:当树非平衡二叉树,在极端的情况下,使用递归栈的空间为O(N),对平衡二叉树而言,递归深度为logN,所以额外空间复杂度为O(N)
执行结果:
路径总和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>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
process(root,sum,res,list);
return res;
}
private void process(TreeNode root,int sum,List<List<Integer>> res,List<Integer> list){
if(root == null){
return;
}
list.add(root.val);
if(root.left == null && root.right == null && sum == root.val){
res.add(new ArrayList<>(list));
}
process(root.left,sum - root.val,res,list);
process(root.right,sum - root.val,res,list);
list.remove(list.size() - 1);
}
}
时间复杂度:O(N)
额外空间复杂度:递归栈最多消耗的额外空间为O(N)
执行结果: