Advertisement
jibha

Untitled

Jan 22nd, 2022
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 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. int Difference(TreeNode* root,int val){
  16. if(root==nullptr){
  17. return INT_MAX;
  18. }
  19.  
  20. if(root->left==nullptr&&root->right==nullptr){
  21. return INT_MAX;
  22. }
  23. if(root->left==nullptr){
  24. return min(abs(root->right->val-val),Difference(root->right,val));
  25. }
  26. if(root->right==nullptr){
  27. return min(abs(root->left->val-val),Difference(root->left,val));
  28. }
  29.  
  30. return min(abs(root->left->val-val),
  31. min(abs(val-root->right->val),
  32. min(Difference(root->right,val),Difference(root->left,val))));
  33.  
  34. }
  35.  
  36. int mini=INT_MAX;
  37.  
  38. int getMinimumDifference(TreeNode* root) {
  39.  
  40. if(root==nullptr){
  41. return INT_MAX;
  42. }
  43.  
  44. if(root->left==nullptr&&root->right==nullptr){
  45. return INT_MAX;
  46. }
  47. if(root->left==nullptr){
  48. return min(mini,min(Difference(root->right,root->right->val)
  49. ,Difference(root,root->val)));
  50. }
  51. if(root->right==nullptr){
  52. return min(mini,min(Difference(root->left,root->left->val),
  53. Difference(root,root->val)));
  54. }
  55.  
  56. return min(min(Difference(root,root->val),mini),
  57. min(Difference(root->left,root->left->val),Difference(root->right,root->right->val)));
  58. }
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement