Skip to content

Instantly share code, notes, and snippets.

@akhilesh-kumar-verma
Last active April 14, 2024 16:56
Show Gist options
  • Save akhilesh-kumar-verma/784b0f0da51106ab816faa0dabb911b8 to your computer and use it in GitHub Desktop.
Save akhilesh-kumar-verma/784b0f0da51106ab816faa0dabb911b8 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode { int val;TreeNode *left;TreeNode*right; TreeNode(int val, TreeNode *left, TreeNode *right):val(val), left(left), right(right) {}; };
// 13 12 21 14 24 10 22 15 23
int main() {
TreeNode *root=new TreeNode(12, new TreeNode(13, nullptr, nullptr), new TreeNode(10, new TreeNode(14, new TreeNode(21, nullptr, nullptr), new TreeNode(24, nullptr, nullptr)), new TreeNode(15, new TreeNode(22, nullptr, nullptr), new TreeNode(23, nullptr, nullptr))));
queue<TreeNode *> Q; Q.push(root); int N1, N2; cin >> N1 >> N2;
bool sameParent=false; size_t d_n1, d_n2;
for (size_t level=0; Q.size() and !sameParent; ++level) {
for (size_t i=Q.size(); i; --i) {
if (Q.front()->val==N1) { d_n1=level; } if (Q.front()->val==N2) { d_n2=level; }
if (Q.front()->left and Q.front()->right and
((Q.front()->left->val==N1 and Q.front()->right->val==N2) or
(Q.front()->left->val==N2 and Q.front()->right->val==N1))) { sameParent=true; break; }
if (Q.front()->left) { Q.push(Q.front()->left); } if (Q.front()->right) { Q.push(Q.front()->right); }
/*cout << Q.front()->val << " " << flush; */ Q.pop(); } /*cout << endl; */ }
cout << (!sameParent and d_n1==d_n2?"YES":"NO") << endl;
return 0; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment