-
SLPHPython中序遍历法:
class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ self.last = -0x80000000 self.ans = 0x7FFFFFFF def inOrderTraverse(root): if not root: return inOrderTraverse(root.left) self.ans = min(self.ans, root.val - self.last) self.last = root.val inOrderTraverse(root.right) inOrderTraverse(root) return self.ans
-
SLPHPython递归法:
class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ left, right = root.left, root.right ans = 0x7FFFFFFF if left: while left.right: left = left.right ans = min(root.val - left.val, self.getMinimumDifference(root.left)) if right: while right.left: right = right.left ans = min(ans, right.val - root.val, self.getMinimumDifference(root.right)) return ans
-
SLPHC++中序遍历法:
class Solution { public: int getMinimumDifference(TreeNode* root) { int res = INT_MAX, pre = -1; inorder(root, pre, res); return res; } void inorder(TreeNode* root, int& pre, int& res) { if (!root) return; inorder(root->left, pre, res); if (pre != -1) res = min(res, root->val - pre); pre = root->val; inorder(root->right, pre, res); } };
-
SLPHC++先序遍历法:
class Solution { public: int getMinimumDifference(TreeNode* root) { int res = INT_MAX; helper(root, INT_MIN, INT_MAX, res); return res; } void helper(TreeNode* root, int low, int high, int& res) { if (!root) return; if (low != INT_MIN) res = min(res, root->val - low); if (high != INT_MAX) res = min(res, high - root->val); helper(root->left, low, root->val, res); helper(root->right, root->val, high, res); } };
-
SLPHC++迭代法:
class Solution { public: int getMinimumDifference(TreeNode* root) { int res = INT_MAX, pre = -1; stack<TreeNode*> st; TreeNode *p = root; while (p || !st.empty()) { while (p) { st.push(p); p = p->left; } p = st.top(); st.pop(); if (pre != -1) res = min(res, p->val - pre); pre = p->val; p = p->right; } return res; } };
-