Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- public:
- int Difference(TreeNode* root,int val){
- if(root==nullptr){
- return INT_MAX;
- }
- if(root->left==nullptr&&root->right==nullptr){
- return INT_MAX;
- }
- if(root->left==nullptr){
- return min(abs(root->right->val-val),Difference(root->right,val));
- }
- if(root->right==nullptr){
- return min(abs(root->left->val-val),Difference(root->left,val));
- }
- return min(abs(root->left->val-val),
- min(abs(val-root->right->val),
- min(Difference(root->right,val),Difference(root->left,val))));
- }
- int mini=INT_MAX;
- int getMinimumDifference(TreeNode* root) {
- if(root==nullptr){
- return INT_MAX;
- }
- if(root->left==nullptr&&root->right==nullptr){
- return INT_MAX;
- }
- if(root->left==nullptr){
- return min(mini,min(Difference(root->right,root->right->val)
- ,Difference(root,root->val)));
- }
- if(root->right==nullptr){
- return min(mini,min(Difference(root->left,root->left->val),
- Difference(root,root->val)));
- }
- return min(min(Difference(root,root->val),mini),
- min(Difference(root->left,root->left->val),Difference(root->right,root->right->val)));
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement