fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct TreeNode{
  4. int val;
  5. vector<TreeNode*>children;
  6. TreeNode(int val):children({}),val(val){};
  7. };
  8. bool find(TreeNode* root,int d){
  9. if(root->val==d){
  10. return true;
  11. }
  12.  
  13. for(auto &child:root->children){
  14. if(child->val == d)return true;
  15. //find(child,d);
  16. }
  17. for(auto &child:root->children){
  18. find(child,d);
  19. }
  20.  
  21. return false;
  22. }
  23. TreeNode* construct(vector<int>&arr){
  24. if(arr.empty()||arr[0]==-1)return nullptr;
  25. TreeNode* root = new TreeNode(arr[0]);
  26. stack<TreeNode*>st;
  27. st.push(root);
  28.  
  29. for(int i = 1;i<arr.size();i++){
  30. auto u = st.top();
  31. if(arr[i]==-1){
  32. st.pop();
  33. }else{
  34. TreeNode* newNode = new TreeNode(arr[i]);
  35. u->children.push_back(newNode);
  36. st.push(newNode);
  37. }
  38. }
  39. return root;
  40. }
  41. int main() {
  42. vector<int>arr = {1,2,4,-1,5,-1,-1,3,6,-1,7,-1,-1,-1};
  43. TreeNode* root = construct(arr);
  44. int d = 4;
  45. bool ans = find(root,d);
  46. cout<<"val : "<<ans<<endl;
  47. return 0;
  48. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
val : 0