递归的本质是找重复的子问题
文章目录
- 1.计算布尔二叉树的值
- 2.从根节点到叶节点数字之和
- 3.二叉树剪枝
- 4.验证二叉搜索树
- 5.二叉搜索树中第K小的元素
- 6.二叉树的所有路径
1.计算布尔二叉树的值
计算布尔二叉树的值
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; }
};
2.从根节点到叶节点数字之和
从根节点到叶节点数字之和
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;}
};
3.二叉树剪枝
二叉树剪枝
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;}
};
4.验证二叉搜索树
验证二叉搜索树
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;}
};
5.二叉搜索树中第K小的元素
二叉搜索树中第K小的元素
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);}
};
6.二叉树的所有路径
二叉树的所有路径
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);}
};
有什么不懂的可以后台直接私信我嗷!