方法:递归
class Solution {
private:
TreeNode* dfs(vector<int>& nums, int l, int r) {
if (l >= r) return nullptr;
int maxidx = l;
for (int i = l + 1; i < r; ++i) if (nums[i] > nums[maxidx]) maxidx = i;
TreeNode* root = new TreeNode(nums[maxidx]);
root->left = dfs(nums, l, maxidx);
root->right = dfs(nums, maxidx + 1, r);
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
int l = 0, r = nums.size();
return dfs(nums, l, r);
}
};
$时间复杂度O(n),空间复杂度O(n);
方法:递归
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == NULL) return root2;
if (root2 == NULL) return root1;
root1->left = mergeTrees(root1->left, root2->left);
root1->val += root2->val;
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};
$时间复杂度O(min(n, m)),空间复杂度O(min(n, m));
方法:迭代
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (!t1) return t2;
if (!t2) return t1;
queue<TreeNode*> q;
q.push(t1);
q.push(t2);
while (!q.empty()) {
TreeNode* nod1 = q.front(); q.pop();
TreeNode* nod2 = q.front(); q.pop();
nod1->val += nod2->val;
if (nod1->left != NULL && nod2->left != NULL) {
q.push(nod1->left);
q.push(nod2->left);
}
if (nod1->right != NULL && nod2->right != NULL) {
q.push(nod1->right);
q.push(nod2->right);
}
if (!nod1->left && nod2->left != NULL) nod1->left = nod2->left;
if (!nod1->right && nod2->right != NULL) nod1->right = nod2->right;
}
return t1;
}
};
$时间复杂度O(min(n, m)),空间复杂度O(min(n, m));
方法:递归
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr) return NULL;
if (root->val > val) return searchBST(root->left, val);
if (root->val < val) return searchBST(root->right, val);
return root;
}
};
$时间复杂度O(n),空间复杂度O(n);
方法:迭代
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == NULL) return NULL;
while (root) {
if (root->val > val) root = root->left;
else if (root->val < val) root = root->right;
else return root;
}
return NULL;
}
};
$时间复杂度O(n),空间复杂度O(n);
方法:迭代
class Solution {
public:
bool isValidBST(TreeNode* root) {
stack<TreeNode*> stk;
TreeNode* cur = root;
TreeNode* pre = NULL;
while (cur != NULL || !stk.empty()) {
if (cur != NULL) {
stk.push(cur);
cur = cur->left;
} else {
cur = stk.top();
stk.pop();
if (pre != NULL && pre->val >= cur->val) return false;
pre = cur;
cur = cur->right;
}
}
return true;
}
};
$时间复杂度O(n),空间复杂度O(n);
方法:递归(中序遍历)
class Solution {
private:
vector<int>res;
void dfs(TreeNode* root) {
if (root == NULL) return;
if (root->left) dfs(root->left);
res.emplace_back(root->val);
if (root->right) dfs(root->right);
}
public:
bool isValidBST(TreeNode* root) {
dfs(root);
for (int i = 1; i < res.size(); ++i) if (res[i] <= res[i-1]) return false;
return true;
}
};
$时间复杂度O(n),空间复杂度O(n);