leecode 112. 路径总和

​​​​​​112. 路径总和

/**
 * 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;
        //if (root.val == targetSum) return true;
        //这一步在输入(1,2),1时错误,因为此时判断了root.val == targetSum,
        //但是实际上结束判断时需要判断是否是叶子节点,只有当是叶子节点时,且
        //最后一层的root.val == targetSum时才为true。
        if (root.left == null && root.right == null && root.val == targetSum) return true;
        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val); 
    }
}


详细版:

class Solution {
   public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        targetSum -= root.val;
        // 叶子结点
        if (root.left == null && root.right == null) {
            return targetSum == 0;
        }
        if (root.left != null) {
            boolean left = hasPathSum(root.left, targetSum);
            if (left) {// 已经找到
                return true;
            }
        }
        if (root.right != null) {
            boolean right = hasPathSum(root.right, targetSum);
            if (right) {// 已经找到
                return true;
            }
        }
        return false;
    }
}



迭代:

class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;
        Queue<TreeNode> queue = new LinkedList<>();
//需要一个容器盛放当前节点的值
        Queue<Integer> queVal = new LinkedList<>();
        queue.offer(root);
        queVal.offer(root.val);
        //int res = 0;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            int tem = queVal.poll();
            //res += tem; 
//当遍历到叶子节点时,判断是否与目标值相等,相等返回true,不相等继续进行,找其他的路径
            if (node.left == null && node.right == null) {
                if (tem == targetSum) {
                    return true;
                }
                continue;
            }
            if (node.left != null) {
                queue.offer(node.left);
                queVal.offer(node.left.val + tem);
            }
            if (node.right != null) {
                queue.offer(node.right);
                queVal.offer(node.right.val + tem);
            }
        }
        return false;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值