力扣--树题总结
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更新到当前节点的valpre = 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);}
};