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了.

Last updated

Was this helpful?