letcode 分类练习 226.翻转二叉树 101. 对称二叉树 104.二叉树的最大深度 111.二叉树的最小深度
- 226.翻转二叉树
- 101. 对称二叉树
- 104.二叉树的最大深度
- 111.二叉树的最小深度
226.翻转二叉树
利用自底向上的遍历交换左子树和右子树
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return nullptr;
TreeNode* left = invertTree(root->left);
TreeNode* right = invertTree(root->right);
root -> left = right;
root -> right = left;
return root;
}
};
101. 对称二叉树
如果是叶子结点返回true,左子树不等于右子树就返回false,然后递归看左子树和右子树也是否满足条件
class Solution {
public:
bool check(TreeNode* left,TreeNode* right){
if((left && !right) || (!left && right) || (left && right && left->val != right -> val))return false;
if(!left && !right) return true;
return check(left -> left, right -> right) && check(left -> right, right -> left);
}
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return check(root->left, root -> right);
}
};
104.二叉树的最大深度
还是递归转化为右子树和左子树的思想,递归转化条件为
d
m
a
x
=
m
a
x
{
d
m
a
x
l
e
f
t
,
d
m
a
x
r
i
g
h
t
}
+
1
d_{max} = max\{d_{max}^{left},d_{max}^{right}\} + 1
dmax=max{dmaxleft,dmaxright}+1
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return 1 + max(maxDepth(root -> left), maxDepth(root -> right));
}
};
111.二叉树的最小深度
还是转换为左子树右子树的最小深度取min
d
m
a
x
=
m
i
n
{
d
m
a
x
l
e
f
t
,
d
m
a
x
r
i
g
h
t
}
+
1
d_{max} = min\{d_{max}^{left},d_{max}^{right}\} + 1
dmax=min{dmaxleft,dmaxright}+1
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
int left_depth = 1 + minDepth(root -> left);
int right_depth = 1 + minDepth(root -> right);
if(left_depth == 1)return right_depth;
else if(right_depth == 1)return left_depth;
return min(left_depth, right_depth);
}
};