力扣--树题总结
783. 二叉搜索树节点最小距离
/**
* 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 {
public:
int minDiffInBST(TreeNode* root) {
int ans = INT_MAX, pre = -1;
dfs(root, pre, ans);
return ans;
}
void dfs(TreeNode* root, int& pre, int& ans){
//递归返回条件
if(root == nullptr){
return;
}
//前-一直递归到左下角
dfs(root->left, pre, ans);
//中-处理数据,第一次pre保存左下角值
if(pre == -1){
pre = root->val;
}else{
//递归退回到左下角父节点,ans取最小
ans = min(ans, root->val - pre);
//pre更新到当前节点的val
pre = root->val;
}
//后续
dfs(root->right, pre, ans);
}
};
872. 叶子相似的树
/**
* 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 {
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector<int> num1;
vector<int> num2;
inorder(root1, num1);
inorder(root2, num2);
if(num1.size() != num2.size()) return false;
for(int i=0; i< num1.size(); i++){
if(num1[i] != num2[i]) return false;
}
return true;
}
void inorder(TreeNode* root, vector<int>& num){
if(root==nullptr){
return;
}
inorder(root->left, num);
if(root->left==nullptr && root->right==nullptr){
num.push_back(root->val);
}
inorder(root->right, num);
}
};
原文地址:https://blog.csdn.net/weixin_44965579/article/details/143691973
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!