方法:递归
/**
* 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 {
private:
int res = INT_MAX;
TreeNode* pre = NULL;
void dfs(TreeNode* cur) {
if (cur == NULL) return;
dfs(cur->left);
if (pre != NULL) res = min(res, cur->val - pre->val);
pre = cur;
dfs(cur->right);
}
public:
int getMinimumDifference(TreeNode* root) {
dfs(root);
return res;
}
};
$时间复杂度O(n),空间复杂度O(n)
方法:迭代
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
int res = INT_MAX;
stack<TreeNode*> st;
TreeNode* cur = root;
TreeNode* pre = NULL;
while (cur != NULL || !st.empty()) {
if (cur != NULL) {
st.push(cur);
cur = cur->left;
} else {
cur = st.top();
st.pop();
if (pre != NULL) res = min(res, cur->val - pre->val);
pre = cur;
cur = cur->right;
}
}
return res;
}
};
$时间复杂度O(n),空间复杂度O(n)
方法:递归
class Solution {
private:
void dfs(TreeNode* cur, unordered_map<int, int>& vis) {
if (cur == NULL) return ;
dfs(cur->left, vis);
++vis[cur->val];
dfs(cur->right, vis);
return ;
}
bool static cmp(const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
}
public:
vector<int> findMode(TreeNode* root) {
vector<int> res;
unordered_map<int, int> vis;
if (root == NULL) return res;
dfs(root, vis);
vector<pair<int, int>> vec(vis.begin(), vis.end());
sort(vec.begin(), vec.end(), cmp);
res.emplace_back(vec[0].first);
for (int i = 1; i < vec.size(); ++i) {
if (vec[i].second == vec[0].second) res.emplace_back(vec[i].first);
else break;
}
return res;
}
};
$时间复杂度O(n),空间复杂度O(n)
方法:迭代
class Solution {
public:
vector<int> findMode(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* cur = root;
TreeNode* pre = NULL;
vector<int> res;
int cnt = 0, maxn = 0;
while (cur != NULL || !st.empty()) {
if (cur != NULL) {
st.push(cur);
cur = cur->left;
} else {
cur = st.top();
st.pop();
if (pre == NULL) cnt = 1;
else if (pre->val == cur->val) ++cnt;
else cnt = 1;
if (cnt == maxn) res.emplace_back(cur->val);
if (cnt > maxn) {
maxn = cnt;
res.clear();
res.emplace_back(cur->val);
}
pre = cur;
cur = cur->right;
}
}
return res;
}
};
$时间复杂度O(n),空间复杂度O(n)
方法:递归
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == p || root == q || root == NULL) return root;
TreeNode* l = lowestCommonAncestor(root->left, p, q);
TreeNode* r = lowestCommonAncestor(root->right, p, q);
if (l != NULL && r != NULL) return root;
if (l == NULL) return r;
return l;
}
};
$时间复杂度O(n),空间复杂度O(n)