I am trying to use dfs with stack iterative approach to this problem.
But I am getting wrong answer on submission, Please can someone help wht case is missing in this code.
Here is my code :
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public bool HasPathSum(TreeNode root, int sum) {
if(root == null) return false;
Stack<TreeNode> st = new Stack<TreeNode>();
st.Push(root);
int pathsum = 0;
while(st.Any())
{
TreeNode curr = st.Pop();
if(curr!= null)
{
pathsum = pathsum + curr.val;
}
if(curr.left != null)
{
st.Push(curr.left);
}
if(curr.right != null)
{
st.Push(curr.right);
}
if(pathsum == sum && curr.left == null && curr.right == null) return true;
if(curr.left == null && curr.right == null)
{
pathsum = root.val;
}
}
return false;
}
}```