二、路径总和
1.深度优先搜索
使用递归的方式遍历二叉树,判断当前节点是否为叶子节点,如果是叶子节点,判断路径和是否等于目标和。如果不是叶子节点,则递归遍历左右子树,直到找到叶子节点或者遍历完整个二叉树。具体代码如下:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public boolean hasPathSum(TreeNode root, int targetSum) {if(root == null) {return false;}int sum = 0;return process(root,targetSum,sum);}public boolean process(TreeNode head,int targetSum,int sum) {if(head == null) {return false; }sum += head.val;if(head.right == null && head.left == null && sum != targetSum) {return false;}if(head.right == null && head.left == null && sum == targetSum) {return true;}return process(head.left,targetSum,sum) || process(head.right,targetSum,sum);}
}
复杂度分析
- 时间复杂度:O(n),其中 n 是二叉树的节点数。在最坏情况下,需要遍历二叉树的所有节点。
- 空间复杂度:O(h),其中 h 是二叉树的高度。空间复杂度主要取决于递归调用的层数,递归调用的层数不会超过树的高度。