当前位置:网站首页>427- binary tree (617. merge binary tree, 700. search in binary search tree, 98. verify binary search tree, 530. minimum absolute difference of binary search tree)
427- binary tree (617. merge binary tree, 700. search in binary search tree, 98. verify binary search tree, 530. minimum absolute difference of binary search tree)
2022-06-27 06:01:00 【liufeng2023】
617. Merge binary tree
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. Search in binary search tree
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. Verify binary search tree
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. The minimum absolute difference of binary search tree
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;
}
};
边栏推荐
猜你喜欢
JVM常用指令
Two position relay xjls-8g/220
KubeSphere 集群配置 NFS 存储解决方案-收藏版
LeetCode-515. Find the maximum value in each tree row
Two position relay rxmvb2 r251 204 110dc
Navigation [machine learning]
openresty使用文档
IAR systems fully supports Centrino technology 9 series chips
C语言练手小项目(巩固加深知识点理解)
双位置继电器DLS-34A DC0.5A 220VDC
随机推荐
Qt使用Valgrind分析内存泄漏
Software testing year end summary report template
C language implementation timer
Win 10 如何打开环境变量窗口
js实现双向数据绑定
【Cocos Creator 3.5.1】event. Use of getbutton()
爬虫学习5---反反爬之识别图片验证码(ddddocr和pytesseract实测效果)
Senior [Software Test Engineer] learning route and necessary knowledge points
【合辑】点云基础知识及点云催化剂软件功能介绍
函数栈帧的形成与释放
Discussion on streaming media protocol (MPEG2-TS, RTSP, RTP, RTCP, SDP, RTMP, HLS, HDS, HSS, mpeg-dash)
我对于测试团队建设的意见
Wechat applet websocket use case
Contents in qlistwidget are not displayed
数据库-索引
表单校验 v-model 绑定的变量,校验失效的解决方案
Junda technology - centralized monitoring scheme for multi brand precision air conditioners
310. 最小高度树
Obtenir le volume du système à travers les plateformes de l'unit é
leetcode298周赛记录