给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
示例 2:
输入:root = [2,1,3] 输出:[2,3,1]
示例 3:
输入:root = [] 输出:[]
提示:
- 树中节点数目范围在
[0, 100]
内 -100 <= Node.val <= 100
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) return root;
invertTree(root->left);
invertTree(root->right);
swap(root->left, root->right);
return root;
}
};
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
提示:
- 树中节点数目在范围
[1, 1000]
内 -100 <= Node.val <= 100
class Solution {
public:
bool cmp(TreeNode* left,TreeNode* right) {
if (left && !right) return false;
else if (!left && right) return false;
else if (!left && !right) return true;
else if (left->val != right->val) return false;
return cmp(left->left, right->right) && cmp(left->right, right->left);
}
bool isSymmetric(TreeNode* root) {
if (!root) return true;
return cmp(root->left, root->right);
}
};
给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:3
示例 2:
输入:root = [1,null,2] 输出:2
提示:
- 树中节点的数量在
[0, 104]
区间内。 -100 <= Node.val <= 100
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
int rightDepth = maxDepth(root->right);
int leftDepth = maxDepth(root->left);
return 1 + max(rightDepth,leftDepth);
}
};