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

判斷某條路徑的加和值是否是等於給定值。node

就像是print路徑同樣ide

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) return false;
        
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            if (cur.left == null && cur.right == null) { //if cur is the leaf node
                if (cur.val == sum) {
                    return true;
                }
            }
            if (cur.right != null) {
                cur.right.val += cur.val; //改變了樹 不得不誰仍是挺經典的
                stack.push(cur.right);
            }
            if (cur.left != null) {
                cur.left.val += cur.val;
                stack.push(cur.left);
            }
        }
        return false;
    }
}
相關文章
相關標籤/搜索