From 4415808d5c54fc50c3e1a4eb7a8f7e05d2114a78 Mon Sep 17 00:00:00 2001 From: keineahnung2345 Date: Mon, 2 Mar 2020 23:56:24 +0800 Subject: [PATCH] 1026. Maximum Difference Between Node and Ancestor.cpp --- ...m Difference Between Node and Ancestor.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 1026. Maximum Difference Between Node and Ancestor.cpp diff --git a/1026. Maximum Difference Between Node and Ancestor.cpp b/1026. Maximum Difference Between Node and Ancestor.cpp new file mode 100644 index 0000000..8c1c8b6 --- /dev/null +++ b/1026. Maximum Difference Between Node and Ancestor.cpp @@ -0,0 +1,26 @@ +//https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/274610/JavaC%2B%2BPython-Top-Down + +//Top Down +//Runtime: 4 ms, faster than 96.94% of C++ online submissions for Maximum Difference Between Node and Ancestor. +//Memory Usage: 11.9 MB, less than 86.36% of C++ online submissions for Maximum Difference Between Node and Ancestor. + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int maxAncestorDiffMM(TreeNode* node, int mx, int mn){ + return node ? max(maxAncestorDiffMM(node->left, max(node->val, mx), min(node->val, mn)), + maxAncestorDiffMM(node->right, max(node->val, mx), min(node->val, mn))): mx-mn; + } + + int maxAncestorDiff(TreeNode* root) { + return maxAncestorDiffMM(root, 0, INT_MAX); + } +};