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