下
最近公共祖先
包含
分了两树
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if(root==nullptr||root==p||root==q)return root;TreeNode *l=lowestCommonAncestor(root->left,p,q);TreeNode *r=lowestCommonAncestor(root->right,p,q);//左树搜到 右树也搜到返回rootif(l!=nullptr&&r!=nullptr)return root;//都没搜到返回空if(l==nullptr&&r==nullptr)return nullptr;//l和r一个空 一个不为空 返回不空的那个return l!=nullptr?l:r;}
};
收集累加和等于aim的路径
/*** 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:vector<vector<int>> pathSum(TreeNode* root, int targetSum) {vector<vector<int>>ans;vector<int>path;if(root){dfs(root,targetSum,0,path,ans);}return ans;}void dfs(TreeNode* cur,int targetSum,int sum,vector<int>&path,vector<vector<int>>&ans){//如果是叶子结点if(cur->left==nullptr&&cur->right==nullptr){if(cur->val+sum==targetSum){path.push_back(cur->val);ans.push_back(path);path.pop_back();}}//如果不是叶子结点else{path.push_back(cur->val);if(cur->left)dfs(cur->left,targetSum,cur->val+sum,path,ans);if(cur->right)dfs(cur->right,targetSum,cur->val+sum,path,ans);path.pop_back();}}
};
验证平衡二叉树
/*** 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 {bool balanced=true;
public:bool isBalanced(TreeNode* root) {height(root);return balanced;}int height(TreeNode* cur){//一旦发现不平衡 返回什么不重要了if(!balanced||cur==nullptr)return 0;int lh=height(cur->left);int rh=height(cur->right);if(abs(lh-rh)>1)balanced=false;return max(lh,rh)+1;}
};
验证二叉搜索树
/*** 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) {}* };*/
long minVal = LONG_MAX; // Global variable to store the minimum value
long maxVal = LONG_MIN;
class Solution {
public:bool isValidBST(TreeNode* head) {if (head == nullptr) {minVal = LONG_MAX;maxVal = LONG_MIN;return true;}bool lok = isValidBST(head->left);long lmin = minVal;long lmax = maxVal;bool rok = isValidBST(head->right);long rmin = minVal;long rmax = maxVal;minVal = std::min({lmin, rmin, static_cast<long>(head->val)});maxVal = std::max({lmax, rmax, static_cast<long>(head->val)});return lok && rok && lmax < head->val && head->val < rmin;
}
};