递归的本质是找重复的子问题
class Solution {
public:
bool evaluateTree(TreeNode* root) {
if(root->left == nullptr) return root->val == 0?false:true;
bool left = evaluateTree(root->left);
bool right = evaluateTree(root->right);
return root->val == 2? left|right:left&right;
}
};
class Solution {
public:
int sumNumbers(TreeNode* root) {
return dfs(root,0);
}
int dfs(TreeNode* root,int prevsum)
{
prevsum = prevsum*10+root->val;
if(root->left == nullptr && root->right == nullptr) return prevsum;
int ret = 0;
if(root->left) ret += dfs(root->left,prevsum);
if(root->right) ret += dfs(root->right,prevsum);
return ret;
}
};
class Solution {
public:
TreeNode* pruneTree(TreeNode* root) {
//后序遍历
if(root == nullptr) return nullptr;
root->left = pruneTree(root->left);
root->right = pruneTree(root->right);
if(root->left == nullptr && root->right == nullptr && root->val == 0)
{
//delete root;//防止内存泄漏,前提是节点是new出来的
root = nullptr;
}
return root;
}
};
class Solution {
//性质:二叉搜索树的中序遍历是一个有序的序列
long prev = LONG_MIN;
public:
bool isValidBST(TreeNode* root) {
if(root == nullptr) return true;
bool left = isValidBST(root->left);
if(left == false) return false;
bool cur = false;
if(root->val>prev)
{
cur = true;
}
if(cur == false) return false;
prev = root->val;
bool right = isValidBST(root->right);
return left && right && cur;
}
};
class Solution {
//性质:二叉搜索树的中序遍历是一个有序的序列
int count;
int ret;
public:
int kthSmallest(TreeNode* root, int k) {
count = k;
dfs(root);
return ret;
}
void dfs(TreeNode* root)
{
if(root == nullptr || count == 0) return;
dfs(root->left);
count --;
if(count == 0) ret = root->val;
dfs(root->right);
}
};
class Solution {
vector<string> ret;
public:
//递归+回溯
vector<string> binaryTreePaths(TreeNode* root) {
string path;
dfs(root,path);
return ret;
}
void dfs(TreeNode* root,string path)
{
path = path+to_string(root->val);
if(root->left == nullptr && root->right == nullptr)
{
ret.push_back(path);
}
path += "->";
if(root->left) dfs(root->left,path);
if(root->right) dfs(root->right,path);
}
};
有什么不懂的可以后台直接私信我嗷!