Advertisement
at3107

Untitled

Oct 23rd, 2020
1,862
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.57 KB | None | 0 0
  1. int ans=0;
  2. int fun(struct TreeNode* node, int k)
  3.     {
  4.         int lk = fun(node.left, k),rk = fun(node.right, k);
  5.         bool isleaf = (lk == -1 && lk == rk);
  6.         if (lk == 0 || rk == 0 || (isleaf && k == 0))
  7.             ans+=node->data;
  8.         if (isleaf && k > 0)
  9.             return k - 1;
  10.         if (lk > 0 && lk < k)
  11.             return lk - 1;
  12.         if (rk > 0 && rk < k)
  13.             return rk - 1;
  14.  
  15.         return -2;
  16.     }
  17.    
  18.     int Kdistance(TreeNode* root,int k)
  19.     {
  20.         if(root==NULL) return -1;
  21.         fun(root,k);
  22.         return ans;
  23.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement