Loading

【力扣】路径总和

 

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例: 
给定如下二叉树,以及目标和 sum = 22

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2

 

方法1.广度优先

public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null){
            return false;
        }
        //路径总和
        //方法一:广度优先搜索
        //节点队列
        Queue<TreeNode> nodeQueue = new LinkedList<>();

        //节点对应的之前的值的和队列
        Queue<Integer> valueQueue = new LinkedList<>();

        //放到队列中
        nodeQueue.offer(root);
        valueQueue.offer(root.val);

        while(!nodeQueue.isEmpty()){
            //从队列中取出节点和值
            TreeNode now = nodeQueue.poll();
            int temp = valueQueue.poll();

            //如果当前节点的左节点和右节点都是空,说明到了最后一层则判断是否同要求的sum相等
            if (now.left == null && now.right == null) {
                if (temp == sum) {
                    return true;
                }

                //这里说明如果中间有某个叶子节点,那么直接跳过,同时,这里也会把他之前增加的数量poll掉
                continue;
            }
            //这样,每一次,
            if (now.left != null){
                nodeQueue.offer(now.left);
                valueQueue.offer(temp + now.left.val);
            }

            if (now.right != null){
                nodeQueue.offer(now.right);
                valueQueue.offer(temp + now.right.val);
            }
        }
        return false;
    }

 

方法二:递归

public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null){
            return false;
        }
        //路径总和
        //方法二:递归
        //假定从根节点到当前节点的值之和为 val,我们可以将这个大问题转化为一个小问题:
        // 是否存在从当前节点的子节点到叶子的路径,满足其路径和为 sum - val

        //如果两个都为空,说明是叶子节点
        if (root.left == null && root.right == null){
            return sum == root.val;
        }
        //递归左节点和右节点
        return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val);
    }

 

posted @ 2020-07-07 22:54  冯廷鑫  阅读(236)  评论(0编辑  收藏  举报