LeetCode 112. Path Sum

题目

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

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

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.


这道题也是终于有思路的一道题,发现自己慢慢摸索出一点点套路来了有点开心!一上来第一反应就是DFS递归,每遍历一个节点就检查它左右子节点底下有没有对应sum - root->val的路径,递归基是当遇到叶子节点且数字满足时return true,而当节点为NULL时return false。刚开始写代码的时候只考虑了数字满足而漏掉了叶子节点的条件,以后要全面考虑。

代码如下,时间16ms,87.07%,空间20M,7.02%:

/*
 * @lc app=leetcode id=112 lang=cpp
 *
 * [112] Path Sum
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if (!root) {
            return false;
        }
        if (root->val == sum && !root->left && !root->right) {
            return true;
        }
        return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
    }
};

2020.10.14 Java 一遍bugfree了

Runtime: 0 ms, faster than 100.00% of Java online submissions for Path Sum.

Memory Usage: 38.9 MB, less than 18.87% of Java online submissions for Path Sum.

/**
 * 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 sum) {
        if (root == null) {
            return false;
        }
        if (root.val == sum && root.left == null && root.right == null) {
            return true;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

2023.1.5

还是bugfree写出来了,开心。


同样,这个递归也可以改成迭代的写法,也是需要两个栈来完成,一个用于存放节点,另一个用于存放剩下的路径应该有的长度。代码也算是比较顺利地写出来了,开心!时间12ms,94.79%,空间20.1M,6.59%。

/*
 * @lc app=leetcode id=112 lang=cpp
 *
 * [112] Path Sum
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if (!root) {
            return false;
        }
        
        stack<TreeNode*> stk;
        stack<int> sums;
        stk.push(root);
        sums.push(sum - root->val);

        while (!stk.empty()) {
            TreeNode* top = stk.top();
            stk.pop();
            int remain_sum = sums.top();
            sums.pop();
            if (remain_sum == 0 && !top->left && !top->right) {
                return true;
            }

            if (top->right) {
                stk.push(top->right);
                sums.push(remain_sum - top->right->val);
            }
            if (top->left) {
                stk.push(top->left);
                sums.push(remain_sum - top->left->val);
            }
        }
        return false;
    }
};

2023.1.5

先写的BFS再写的DFS,嗯,确实是一模一样的,只是把数据结构换了。我写的这种是先右后左的preorder。

/**
 * 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 sum) {
        if (root == null) {
            return false;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        Map<TreeNode, Integer> map = new HashMap<>();
        stack.push(root);
        map.put(root, sum);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            int remain = map.get(node);
            if (node.val == remain && node.left == null && node.right == null) {
                return true;
            }
            if (node.left != null) {
                stack.push(node.left);
                map.put(node.left, remain - node.val);
            }
            if (node.right != null) {
                stack.push(node.right);
                map.put(node.right, remain - node.val);
            }
        }
        return false;
    }
}

 


同样,这道题还可以用BFS做,需要两个queue,除了存放节点以外还要存放剩余的值,写起来跟DFS迭代几乎一毛一样了,感觉有点无聊了……时间24ms,17.85%,空间20.1M,5.06%,感觉这道题我做的空间效率都不行啊 

/*
 * @lc app=leetcode id=112 lang=cpp
 *
 * [112] Path Sum
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if (!root) {
            return false;
        }
        
        queue<TreeNode*> q;
        queue<int> sums;
        q.push(root);
        sums.push(sum - root->val);

        while (!q.empty()) {
            TreeNode* front = q.front();
            q.pop();
            int remain_sum = sums.front();
            sums.pop();

            if (remain_sum == 0 && !front->left && !front->right) {
                return true;
            }

            if (front->left) {
                q.push(front->left);
                sums.push(remain_sum - front->left->val);
            }
            if (front->right) {
                q.push(front->right);
                sums.push(remain_sum - front->right->val);
            }
        }
        return false;
    }
};

2023.1.5

BFS的迭代先写出来了,没有用两个queue,而是采用一个queue存TreeNode,一个map存TreeNode到剩余值的mapping。也bugfree了,开心。

/**
 * 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 sum) {
        if (root == null) {
            return false;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        Map<TreeNode, Integer> map = new HashMap<>();
        queue.add(root);
        map.put(root, sum);
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            int remain = map.get(node);
            if (node.val == remain && node.left == null && node.right == null) {
                return true;
            }
            if (node.left != null) {
                queue.add(node.left);
                map.put(node.left, remain - node.val);
            }
            if (node.right != null) {
                queue.add(node.right);
                map.put(node.right, remain - node.val);
            }
        }
        return false;
    }
}


除此之外还看到个用后序遍历做的,但是好像挺复杂的样子,放弃。(链接:LeetCode - The World's Leading Online Programming Learning Platform

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值