递归基础
待补充
二叉树的最大深度
问题:给定一棵二叉树,求出其最大深度
解:
/**
* 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) {}
* };
*/
int maxDepth(TreeNode *root)
{
if(root == nullptr)
return 0;
else
return max(maxDepth(root->left),maxDepth(root->right)) + 1;
}
平衡二叉树
问题:给定一棵二叉树,判断是否是高度平衡的二叉树
平衡二叉树:每个节点的左右两棵子树的高度差的绝对值不超过1
该问题是在 求二叉树最大深度 基础上延伸扩展的
自顶向下的递归
class Solution {
public:
int height(TreeNode *root)
{
if (!root)
return 0;
else
return max(height(root->left),height(root->right))+1;
}
bool isBalanced(TreeNode* root) {
if(root == nullptr)
return true;
else
return abs(height(root->left) - height(root->right)) <=1 && isBalanced(root->left) && isBalanced(root->right);
}
};
斐波那契数列
递归
递归存在超时问题
class Solution{
public:
int fib(int n)
{
if(n<=1)
return n;
else
return fib(n-1) + fib(n-2);
}
};
迭代
class Solution {
public:
int fib(int n) {
if (n <= 1)
return n;
int cur = 1, pre = 0;
for (int i = 1; i < n; i++)
{
int sum = (cur + pre) %1000000007;
pre = cur;
cur =sum;
}
return cur;
}
};