今天都是重复的题,都还比较简单
给你一棵二叉树的根节点 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 = [] 输出:[]
递归法简单
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;
}
};
给你一个二叉树的根节点 root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false
写这题差点又忘了判空的状态
class Solution {
public:
bool order(TreeNode * a,TreeNode * b)
{
if(a == NULL && b != NULL) return false;
else if(a != NULL && b == NULL) return false;
else if(a == NULL && b == NULL) return true;//注意这个的位置,需要先判空了在判断后面的
else if(a->val != b->val ) return false;
else
{
bool x = order(a->left,b->right);
bool y = order(a->right,b->left);
return x&&y;
}
}
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
return order(root->left,root->right);
}
};
给定一个二叉树 root
,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:3
示例 2:
输入:root = [1,null,2] 输出:2
递归法简单,层次遍历直观
class Solution {
public:
int getDepth(TreeNode * cur,int &depth)
{
if(cur == NULL) return 0;
int leftdepth = getDepth(cur->left,depth);
int rightdepth = getDepth(cur->right,depth);
depth = 1 + max(leftdepth,rightdepth);
return depth;
}
int maxDepth(TreeNode* root) {
int depth = 0;
return getDepth(root,depth);
}
};
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6] 输出:5
小心不要犯经典错误
class Solution {
public:
int getDepth(TreeNode * cur,int &depth)
{
if(cur == NULL) return 0;
int leftdepth = getDepth(cur->left,depth);
int rightdepth = getDepth(cur->right,depth);
// depth = 1 + min(leftdepth,rightdepth);经典的错误,标准的零分
if(cur->left == NULL && cur->right != NULL) return (1 + rightdepth);
if(cur->right == NULL && cur->left != NULL) return (1 + leftdepth);
depth = 1 + min(leftdepth,rightdepth);
return depth;
}
int minDepth(TreeNode* root) {
int depth = 0;
return getDepth(root,depth);
}
};