Path Sum

https://leetcode.com/problems/path-sum/description/

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.

Thoughts

先想分治。从当前结点到叶有sum的path意味着它的左/右结点到叶有sum-node.val的path。

Errors: 1. node == null代表父节点是叶节点。

Code

/**
 * Definition for a binary tree node.
 * 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.val == sum && root.left == null && root.right == null) {
            return true;
        }

        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

Analysis

一次分治遍历O(n).

Ver.2

因为要区分不同的path, iterative 版本inorder traversal能很好的记录path信息. 当退回到中间节点时, 不能直接pop, 否则path将不再包含它, 而是要检查它的右子树是否存在, 并把右子树pushLeft. 但如果每次都pushLeft则无法正常让中间节点退出, 因此还要把上个退出的节点记下来, 看是否和中间节点的right一致, 当一致时意味着右子树已经查过了, 不需要再pushLeft了.

/**
 * 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) {
        stack<TreeNode*> s;
        int psum = 0;
        const auto push_left = [&](TreeNode *cur) {
            while (cur != NULL) {
                psum += cur->val;
                s.push(cur);
                cur = cur->left;
            }
        };
        push_left(root);
        TreeNode *pre = NULL;
        while (!s.empty()) {
            const auto cur = s.top();
            if (cur->left == NULL && cur->right == NULL && psum == sum) return true;
            if (cur->right != NULL && cur->right != pre) {
                push_left(cur->right);
                continue;
            }
            s.pop();
            pre = cur;
            psum -= cur->val;
        }
        return false;
    }
};

Last updated