当前位置:网站首页>427-二叉树(617.合并二叉树、700.二叉搜索树中的搜索、98. 验证二叉搜索树、530.二叉搜索树的最小绝对差)
427-二叉树(617.合并二叉树、700.二叉搜索树中的搜索、98. 验证二叉搜索树、530.二叉搜索树的最小绝对差)
2022-06-27 05:59:00 【liufeng2023】
617.合并二叉树

class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == nullptr) return root2;
if (root2 == nullptr) return root1;
root1->val += root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};

700.二叉搜索树中的搜索

class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr || root->val == val) return root;
if (root->val > val) return searchBST(root->left, val);
if (root->val < val) return searchBST(root->right, val);
return nullptr;
}
};

98. 验证二叉搜索树

class Solution {
private:
vector<int> res;
void traversal(TreeNode* root)
{
if (root == nullptr) return;
traversal(root->left);
res.push_back(root->val);
traversal(root->right);
}
public:
bool isValidBST(TreeNode* root) {
res.clear();
traversal(root);
for (int i = 1; i < res.size(); i++)
{
if (res[i - 1] < res[i])
{
continue;
}
else
{
return false;
}
}
return true;
}
};

530.二叉搜索树的最小绝对差

class Solution {
private:
vector<int> res;
void traversal(TreeNode* root)
{
if (root == nullptr) return;
traversal(root->left);
res.push_back(root->val);
traversal(root->right);
}
public:
int getMinimumDifference(TreeNode* root) {
res.clear();
traversal(root);
if (res.size() < 2) return 0;
int result = INT_MAX;
for (int i = 1; i < res.size(); i++)
{
result = std::min(result, res[i] - res[i - 1]);
}
return result;
}
};

边栏推荐
猜你喜欢

Double position relay rxmd2-1mrk001984 dc220v

30个单片机常见问题及解决办法!

微信小程序WebSocket使用案例

IAR Systems全面支持芯驰科技9系列芯片

Implementation of easyexcel's function of merging cells with the same content and dynamic title

LeetCode-515. 在每个树行中找最大值

cpu-z中如何查看内存的频率和内存插槽的个数?

Small program of C language practice (consolidate and deepen the understanding of knowledge points)

My opinion on test team construction

美摄云服务方案:专为轻量化视频制作场景打造
随机推荐
LeetCode-515. 在每个树行中找最大值
Webrtc series - Nomination and ice of 7-ice supplement for network transmission_ Model
Create a basic WDM driver and use MFC to call the driver
块级元素&行内元素
使用域名转发mqtt协议,避坑指南
JS to implement bidirectional data binding
WebRTC系列-網絡傳輸之7-ICE補充之提名(nomination)與ICE_Model
Double position relay rxmd2-1mrk001984 dc220v
IAR Systems全面支持芯驰科技9系列芯片
双位置继电器XJLS-8G/220
Two position relay hjws-9440
【Cocos Creator 3.5.1】event.getButton()的使用
leetcode299周赛记录
JVM常用指令
Unity中跨平台获取系统音量
Small program of C language practice (consolidate and deepen the understanding of knowledge points)
Spark 之 built-in functions
【Cocos Creator 3.5.1】event. Use of getbutton()
竣达技术丨多品牌精密空调集中监控方案
1317. convert an integer to the sum of two zero free integers