1.翻转二叉树
1.1 题目
1.2 题解
class Solution
{
public:
TreeNode* invertTree(TreeNode* root)
{
if (root == nullptr)return root;
//前序遍历
swap(root->right, root->left);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
class Solution
{
public:
TreeNode* invertTree(TreeNode* root)
{
if (root == nullptr)return root;
//后序遍历
invertTree(root->left);
invertTree(root->right);
swap(root->right, root->left);
return root;
}
};
class Solution
{
public:
TreeNode* invertTree(TreeNode* root)
{
if (root == nullptr)return root;
//中序遍历
invertTree(root->left);
swap(root->right, root->left);
invertTree(root->left);
return root;
}
};
2.对称二叉树
2.1 题目
2.2 题解
class Solution {
public:
bool isSymmetric(TreeNode* root)
{
if (root == nullptr)return true;
bool result = comparetree(root->left, root->right);
return result;
}
bool comparetree(TreeNode* left, TreeNode* right)
{
if (left == nullptr && right == nullptr)return true;
if (left == nullptr && right != nullptr)return false;
if (left != nullptr && right == nullptr)return false;
if (left ->val !=right->val)return false;
bool inside = comparetree(left->left, right->right);
bool outside = comparetree(left->right, right->left);
if (inside == true && outside == true)
{
return true;
}
return false;
}
};
3.二叉树的最大深度
3.1 题目
3.2 题解
class Solution {
public:
int maxDepth(TreeNode* root)
{
if (root == nullptr)return 0;
int leftHeight = maxDepth(root->left);
int rightHeight = maxDepth(root->right);
int result = 1 + max(leftHeight, rightHeight);
return result;
}
};
这题之前做过,这次采用递归的方式做。
4.二叉树的最小深度
4.1 题目
4.2 题解
class Solution {
public:
int minDepth(TreeNode* root)
{
//确定终止条件
if (root == nullptr)return 0;
int leftHeight = minDepth(root->left);
int rightHeight = minDepth(root->right);
//如果左节点为空右节点不为空或者左节点为空右节点不为空
if (root->left == nullptr && root->right != nullptr)
{
return rightHeight + 1;
}
if (root->left != nullptr && root->right == nullptr)
{
return leftHeight + 1;
}
return 1 + min(leftHeight, rightHeight);
}
};
也是用递归。