Advertisement
nikunjsoni

1530

Apr 27th, 2021
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 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. int ans = 0;
  14. public:
  15.     int countPairs(TreeNode* root, int distance) {
  16.         dfs(root, distance);
  17.         return ans;
  18.     }
  19.    
  20.     vector<int> dfs(TreeNode *node, int distance){
  21.         vector<int> dist(11, 0);
  22.         if(!node) return dist;
  23.        
  24.         // Leaf node.
  25.         if(!node->left && !node->right){
  26.             dist[1] = 1;
  27.             return dist;
  28.         }
  29.        
  30.         vector<int> left = dfs(node->left, distance);
  31.         vector<int> right = dfs(node->right, distance);
  32.        
  33.         // Check for all possible combinations and update the answer.
  34.         for(int i=0; i<=10;  i++)
  35.             for(int j=0; j<=10; j++)
  36.                 if(i+j <= distance)
  37.                     ans += left[i]*right[j];
  38.        
  39.         // Update distance array.
  40.         for(int i=0; i<10; i++)
  41.             dist[i+1] = left[i]+right[i];
  42.        
  43.         return dist;
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement