Advertisement
nikunjsoni

1026

Apr 24th, 2021
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 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.     int maxAncestorDiff(TreeNode* root) {
  15.         return dfs(root, root->val, root->val);
  16.     }
  17.    
  18.     int dfs(TreeNode* node, int curMax, int curMin){
  19.         if(!node) return curMax-curMin;
  20.         curMax = max(curMax, node->val);
  21.         curMin = min(curMin, node->val);
  22.         return max(dfs(node->left, curMax, curMin), dfs(node->right, curMax, curMin));
  23.     }
  24.    
  25. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement