Advertisement
Jathin

Untitled

Sep 28th, 2021
706
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. /**
  2.  * Definition for binary tree
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10. vector<int> Solution::solve(TreeNode* A, int B) {
  11.    queue<TreeNode*> q;
  12.    q.push(A);
  13.    vector<int>vec;
  14.    while(!q.empty()){
  15.        int n = q.size();
  16.        bool found  = false;
  17.        while(n--){
  18.            TreeNode* x = q.front();
  19.            q.pop();
  20.            if((x->left && x->left->val == B) ||(x->right && x->right->val == B))
  21.              found  = true;
  22.            else{
  23.                if(x->left)
  24.                  q.push(x->left);
  25.                if(x->right)
  26.                  q.push(x->right);
  27.            }
  28.        }
  29.        if(found){
  30.            while(!q.empty()){
  31.              vec.push_back(q.front()->val);
  32.              q.pop();
  33.            }
  34.            break;
  35.        }
  36.    }
  37.    return vec;
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement