Advertisement
jibha

Untitled

Jan 31st, 2022
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14.  
  15. map<TreeNode*,TreeNode*> parent;
  16. unordered_map<TreeNode*,int> leaves;
  17.  
  18. void parentMaker(TreeNode* root){
  19.  
  20. if(root==nullptr){
  21. return;
  22. }
  23.  
  24. if(root->left!=nullptr){
  25. parent[root->left]=root;
  26.  
  27. }
  28. if(root->right!=nullptr){
  29. parent[root->right]=root;
  30. }
  31.  
  32. parentMaker(root->left);
  33. parentMaker(root->right);
  34. return;
  35. }
  36.  
  37. void leafMaker(TreeNode* root){
  38.  
  39. if(root==nullptr){
  40. return;
  41. }
  42.  
  43. if(root->left==nullptr&&root->right==nullptr){
  44. leaves[root]=1;
  45. return;
  46. }
  47.  
  48. leafMaker(root->left);
  49. leafMaker(root->right);
  50.  
  51. return;
  52. }
  53.  
  54. map<TreeNode*,int> visited;
  55. int ans=0;
  56. int dist;
  57. void dfs(TreeNode* root,int depth,TreeNode* original){
  58.  
  59. if(root==nullptr){
  60. return;
  61. }
  62. visited[root]=1;
  63. if(leaves[root]==1&&root!=original){
  64. if(depth<=dist){
  65. // cout<<original->val<<':'<<root->val<<":"<<depth<<endl;
  66. ans++;
  67. }else{
  68. return;
  69. }
  70. }
  71.  
  72. if(visited[parent[root]]==0){
  73. dfs(parent[root],depth+1,original);
  74. }
  75. if(visited[root->left]==0){
  76. dfs(root->left,depth+1,original);
  77. }
  78.  
  79. if(visited[root->right]==0){
  80. dfs(root->right,depth+1,original);
  81. }
  82.  
  83. return;
  84. }
  85.  
  86.  
  87. int countPairs(TreeNode* root, int distance) {
  88.  
  89. parentMaker(root);
  90. leafMaker(root);
  91. dist=distance;
  92.  
  93.  
  94. for(auto iter:leaves){
  95. visited.clear();
  96. dfs(iter.first,0,iter.first);
  97.  
  98. }
  99.  
  100.  
  101.  
  102. return ans/2;
  103. }
  104. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement