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.
判断某条路径的加和值是不是等于给定值。
就像是print路径一样
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;
}
}

浙公网安备 33010602011771号