112.path sum leetcode wong answer for two test cases - c++

problem My code fails for the following test case. I don't understand why. Can you tell me where I went wrong? My code passes (114/116) test cases. I'm doing DFS and checking whether currSum==targetSum and if it satisfies this condition and it's also a leaf node I'm setting global variable ```flag=true``.
[1,-2,-3,1,3,-2,null,-1]
-1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool flag=false;
void dfs(TreeNode *root, int currSum, int targetSum){
if(root==NULL) return ;
// cout<<currSum<<" ";
currSum+=root->val;
cout<<currSum<<" ";
if(currSum == targetSum) {
if(root->left==NULL && root->right==NULL) flag=true;
return;
}
// else if(abs(currSum)>abs(targetSum)) return;
dfs(root->left,currSum,targetSum);
dfs(root->right,currSum,targetSum);
}
bool hasPathSum(TreeNode* root, int targetSum) {
int currSum=0;
dfs(root,currSum,targetSum);
return flag;
}
};

Here is a simple intuitive solution for Path Sum Leetcode
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(!root) return false;
if(!root->right && !root->left) return root->val==sum;
return hasPathSum(root->left, sum-root->val) ||
hasPathSum(root->right, sum-root->val);
}
};

The code works fine and the logic is perfect, you forgot to put brackets to the if statement
if(root->left == NULL && root->right == NULL) {
flag=true;
return;
}
Here's the full code
class Solution {
public:
bool flag = false;
void dfs(TreeNode *root, int currSum, int targetSum){
if(root == NULL) return ;
currSum += root->val;
if(currSum == targetSum) {
if(root->left==NULL && root->right==NULL) {
flag=true;
return;
}
}
dfs(root->left,currSum,targetSum);
dfs(root->right,currSum,targetSum);
}
bool hasPathSum(TreeNode* root, int targetSum) {
int currSum=0;
dfs(root,currSum,targetSum);
return flag;
}
};

if(root->left==NULL && root->right==NULL) flag=true;
return;
This is wrong. You will return even if the condition doesn't satisfy. As there are negative values, it might be possible that the sum becomes targetSum again at a leaf node after further operations.
Correct:
if(root->left==NULL && root->right==NULL){
flag = true;
return;
}

Related

My code is showing 'true' as output instead of 'False'

So there is a question in Leetcode in which we need to tell whether two binary trees are identical or not. So my function is working correctly for the inputs [1,2,3] and [1,2,3]
but it is printing 'true' for the inputs [1,2] and [1,NULL,2] instead of printing 'false'. Please can anyone tell me what have i done wrong in this program.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* enter code here TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
bool isSameTree(TreeNode *p, TreeNode *q)
{
if (p == NULL && q == NULL)
return true;
if (p != NULL && q != NULL)
{
if (p->val != q->val)
return false;
else
{
isSameTree(p->left, q->left);
isSameTree(p->right, q->right);
}
return true;
}
else
return false;
}
};
You're completely ignoring the results of those recursive calls. The point using recursion here is that two trees are the same if:
Their values are the same AND
Their respective children are the same.
You're testing the former, but never reaping the results of the latter. In reality, what you really should be trying to do is this:
class Solution
{
public:
bool isSameTree(const TreeNode *p, const TreeNode *q)
{
if (p == q) // same actual tree or both NULL
return true;
if (p != NULL && q != NULL)
{
return p->val == q->val &&
isSameTree(p->left, q->left) &&
isSameTree(p->right, q->right);
}
return false;
}
};

Error showing throwing an instance of std::out_of_range

I am solving leetcode question : Cousins in Binary Tree
Link for problem statement: https://leetcode.com/problems/cousins-in-binary-tree/
Logic:
Implementing bfs from root node and storing the distance of each child node from the root node in a "dis" vector and storing each node's parent node in a vector "pred" .
If parent node is not same and distance of x and y in function isCousin is same , then return true else false.
MY CODE:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> dis={0};
vector<int> pred={-1};
// vector<bool> vis={false};
struct TreeNode *temproot,*curr;
void bfs(TreeNode *root){
queue<TreeNode*> q;
int initDis=0;
q.push(root);
// vis.push_back(true);
dis.push_back(0);
pred.push_back(-1);
while(!q.empty()){
curr=q.front();
q.pop();
initDis += 1;
if(curr->left != NULL){
pred.push_back(curr->val);
temproot=curr->left;
// vis.push_back(true);
dis.push_back(initDis);
q.push(temproot);
}
else continue;
if(curr->right != NULL){
pred.push_back(curr->val);
temproot=curr->right;
// vis.push_back(true);
dis.push_back(initDis);
q.push(temproot);
}
else continue;
}
}
bool isCousins(TreeNode* root, int x, int y) {
if(root==NULL) return false;
bfs(root);
if(pred.at(x-1) == pred.at(y-1)) return false;
else
if(dis.at(x-1) == dis.at(y-1)) return true;
else return false;
}
};
ERROR MESSAGE:
Runtime Error Message:
terminate called after throwing an instance of 'std::out_of_range'
Last executed input:
[1,2,3,null,4,null,5]
5
4

Node* vs Node in main

I am coding a binary search tree.
class Node {
public:
Node* left;
Node* right;
int data;
Node(int x) : data(x) {}
void insert(int value) {
if (value < data) {
if (left == NULL)
left = new Node(value);
else
left->insert(value);
} else {
if (right == NULL)
right = new Node(value);
else
right->insert(value);
}
}
bool contains(int value) {
if (value == data)
return true;
else if (value < data) {
if (left == NULL)
return false;
else
return left->contains(value);
} else {
if (right == NULL)
return false;
else
return right->contains(value);
}
}
};
When I use Node x in the main program and then call x.insert(15) it gives a segmentation error. If I use Node* x=new Node(10) and then use x->insert(15) instead then it works fine. What is the reasoning behind that?
int main() {
Node x(10);
x.insert(15);
}
The main problem is that you don't initialize the pointers (left and right) with nullptr but you assume they are initialized with a null pointer in insert. Doing the initialization in the constructor fixes the issue:
Node(int x) : data{x}, left{nullptr}, right{nullptr} {}

Search function returns the same regardless of item present in the binary search tree

Here is my code:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>
struct tree_node
{
tree_node *left;
tree_node *right;
int data;
char r;
} ;
class bst
{
tree_node *root;
public:
bst()
{
root=NULL;
}
int isempty()
{
return(root==NULL);
}
void insert(int item);
void inordertrav();
void inorder(tree_node *);
void postordertrav();
void postorder(tree_node *);
void preordertrav();
void preorder(tree_node *);
int search(tree_node * ,int);
};
void bst::insert(int item)
{
tree_node *p=new tree_node;
tree_node *previous;
p->data=item;
p->left=NULL;
p->right=NULL;
previous=NULL;
if(isempty())
root=p;
else
{
tree_node *current;
current=root;
while(current!=NULL)
{
previous=current;
if(item<current->data)
current=current->left;
else
current=current->right;
}
if(item<previous->data)
previous->left=p;
else
previous->right=p;
}
}
int bst::search(tree_node* root,int data) {
int r;
if(root == NULL) {
// r='f';
return 0;
}
else if (root != NULL){
if(root->data == data) {
// r='t';
return 1;
}
}
else if(data <= root->data) {
return search(root->left,data);
}
else {
return search(root->right,data);
}
}
void main()
{
int digit;
bst b;
tree_node *root;
/*b.insert(52);
b.insert(25);
b.insert(50);
b.insert(15);
b.insert(40);
b.insert(45);
b.insert(20); */
cout<<"insert the nodes in the BT";
cout<<"enter integer: to quit enter 0";
cin>>digit;
while (digit!=0)
{
b.insert(digit);
cin>>digit;
}
cout<<"inorder"<<endl;
b.inordertrav();
cout<<endl<<"postorder"<<endl;
b.postordertrav();
cout<<endl<<"preorder"<<endl;
b.preordertrav();
int number;
cout<<"Enter number be searched\n";
cin>>number;
//If number is found, print "FOUND"
int c;
c=b.search(root,number);
cout<<"returned value"<<c;
if (c==1) cout<<"Found\n";
else cout<<"Not Found\n";
getch();
}
The search function is always returning the same value whether it is in the BST or not.
Please help me to figure out the error.
The above code has no compilation error.
All other functions except search function are working fine.
But the search function is not working as required to search whether the element is in the Binary Search tree or not.
Your code invoke UB.
tree_node *root;
...
c=b.search(root,number); // root is uninitialized
To solve this add a new function:
class bst
{
...
int search(tree_node * ,int);
int search(int v) {
return search(root, v);
}
};
Also in bst::search function:
else //if (root != NULL){ Comment this condition
if(root->data == data) {
// r='t';
return 1;
}
//} Comment this line
This condition is not only redundant but also make some code flow paths return without value.

leetcode Binary Tree Preorder Traversal WA: Input:{1} Output:1 Expected:[1]

I surely return a vector ,but the judging system seems to ignore it and puts my output without "[]".
Could any one help me?
Here is my code:
/**
* Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode*> s;
vector<int> ans;
if(!root)
return ans;
while(root || !s.empty())
{
if(root)
{
cout<<root->val<<endl;
ans.push_back(root->val);
s.push(root);
root = root->left;
}
else
{
root = s.top();
s.pop();
root = root->right;
}
}
return ans;
}
};