今日记录
226.翻转二叉树
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
思路:使用递归法(以前序遍历交换左右节点)
1.确定递归函数的参数和返回值;
2.确定终止条件;
3.确定单层递归的逻辑
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == NULL)
return root;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
使用层序遍历的方式:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL)
que.push(root);
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
swap(node->left, node->right);
if (node->left)
que.push(node->left);
if (node->right)
que.push(node->right);
}
}
return root;
}
};
101.对称二叉树
给你一个二叉树的根节点 root , 检查它是否轴对称。
class Solution {
public:
// 1.确定递归参数的参数和返回值
bool compare(TreeNode* left, TreeNode* right) {
// 2.确定终止条件:左右一方为空时,或者左右不为空但值不相等时
// 两边left和right都为NULL时,返回true
if (left == NULL && right != NULL)
return false;
else if (left != NULL && right == NULL)
return false;
else if (left == NULL && right == NULL)
return true;
else if (left->val != right->val)
return false;
// 3.单层递归的逻辑
bool outside = compare(left->left, right->right); // 输入左节点的左孩子,右节点的右孩子
bool inside = compare(left->right, right->left);
bool isSame = outside && inside;
return isSame;
}
bool isSymmetric(TreeNode* root) {
if (root == NULL)
return true;
bool same = compare(root->left, root->right);
return same;
}
};
104.二叉树的最大深度
给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
return 0;
int leftdepth = maxDepth(root->left);
int rightdepth = maxDepth(root->right);
int depth = 1 + max(leftdepth, rightdepth);
return depth;
}
};
111.二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)
return 0;
int leftdepth = minDepth(root->left);
int rightdepth = minDepth(root->right);
if (root->left == NULL && root->right != NULL)
return 1 + rightdepth;
if (root->left != NULL && root->right == NULL)
return 1 + leftdepth;
int depth = 1 + min(leftdepth, rightdepth);
return depth;
}
};
注意添加的判决条件,必不可少