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.
Approach1: DFS
This problem is quite similar to the LeetCode104, I use two stacks, one for node and one for node value. This is a pre-order idea to process nodes. Each time when I process the node, I process the value of it and update the sum of it. Cause the problem is asked about the root-leaf. I thought a valid path is right. that's the mistake I made at first. So I need to check if the node has child even if the value is equal to sum.
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
Stack<TreeNode> stack = new Stack<>();
Stack<Integer> value = new Stack<>();
stack.push(root);
value.push(root.val);
while(!stack.empty()){
TreeNode node = stack.pop();
int temp = value.pop();
if(temp == sum && node.left == null && node.right == null) {//follow up may exist here
return true;
}
if(node.left != null){
stack.push(node.left);
value.push(node.left.val + temp);
}
if(node.right != null){
stack.push(node.right);
value.push(node.right.val + temp);
}
}
return false;
}
}
Follow up question my be like: Find a valid path is fine, no need to root-leaf. Then just remove the condition "node.left == null && node.right == null".
Approach2 Recursion
The basic idea is to subtract the value of current node from sum until it reaches a leaf node and the subtraction equals 0, then we know that we got a hit. Otherwise the subtraction at the end could not be 0. Recursion pattern goes like update the parameter while call it self.
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(root.left == null && root.right == null && sum - root.val == 0) return true;
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。