[leetCode]112.路径总和

在这里插入图片描述

递归

判断根节点到叶子结点路径上的和是否为sum 可以转化为子树根结点到叶子节点的和是否为sum-root.val,所以若当前结点是叶子结点只需要判断叶子节点的值是否为sum,否则递归处理子问题

 * 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;
        else return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

广度优先搜索

使用两个队列,一个用于遍历结点,另一个用于遍历当前结点到根结点的路径之和。

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) return false;
        Queue<TreeNode> queNode = new LinkedList<>();
        Queue<Integer>  queInt  = new LinkedList<>();
        queNode.offer(root);
        queInt.offer(root.val);
        while(!queNode.isEmpty()){
            TreeNode x = queNode.poll();
            int temp = queInt.poll();//用于保存x及x之前的路径和
            if(x.left == null && x.right == null && temp == sum){
                return true;
            }
            if(x.left!=null){
                queNode.offer(x.left);
                queInt.offer(x.left.val + temp);
            }
             if(x.right!=null){
                queNode.offer(x.right);
                queInt.offer(x.right.val + temp);
            }
        }
        return false;
    }
}

也可以不使用两个队列,使用一个队列,元素变为键值对,值保存的是到当前结点的路径和

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root == null) return false;
        Queue<Pair<TreeNode, Integer>> queNode = new LinkedList<>();
        queNode.offer(new Pair(root, root.val));//每个结点对应一条路径值
        while(!queNode.isEmpty()){
            Pair<TreeNode, Integer> x = queNode.poll();
            TreeNode cur = x.getKey();
            int pathSum = x.getValue();
            if(cur.left == null && cur.right == null && pathSum == sum){
                return true;
            }
            if(cur.left!=null){
                queNode.offer(new Pair(cur.left,cur.left.val + pathSum));
            }
             if(cur.right!=null){
                 queNode.offer(new Pair(cur.right,cur.right.val + pathSum));
            }
        }
        return false;
    }
}
posted @ 2020-07-10 10:26  消灭猕猴桃  阅读(56)  评论(0编辑  收藏  举报