226.翻转二叉树
迭代:迭代是一种重复执行的过程,通常用于逐步改进或优化某个系统、算法或模型。迭代适用于那些可以明确划分为一系列重复步骤的问题,如遍历数组、计算累加和等。
递归:递归是一种通过函数调用自身来解决问题的编程技巧。递归适用于那些具有自相似性的问题,即问题可以分解为与原问题相似的规模较小的问题。例如,二叉树的遍历、排序算法(如归并排序)等都可以使用递归来实现。
递归法
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL) return root;//递归至传入根节点root为空时返回
//root == NULL 和 !root 逻辑等价 (当root为空指针时,if判断结果同样为真)
swap(root->left,root->right);//前序遍历 中左右
invertTree(root->left);
invertTree(root->right);
return root;
}
};
层序遍历-广度优先搜索(BFS,Breadth First Search)
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. 对称二叉树
是否为对称二叉树不可以通过简单翻转后对比树结构是否相等来判断。
在 C++ 中,
TreeNode*
是指针类型,直接比较两个指针是否相等。只检查它们是否指向内存中的同一个位置,而不是检查它们指向的树结构是否相同。因此,直接比较翻转后是否相等无法正确判断两棵树是否结构相同。
class Solution {
public:
bool compare(TreeNode* left,TreeNode* right){
if(left==nullptr && right==nullptr) return true;
else if(!left && right) return false;
else if(left && !right) return false;
else if(left->val!=right->val) return false;
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==nullptr) return true;
return compare(root->left,root->right);
}
};
注意如何递归
104.二叉树的最大深度
class Solution {
public:
//递归法
int getHeight(TreeNode* root){
if(root==nullptr) return 0;
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
int height = 1 + max(leftHeight,rightHeight);
return height;
}
int maxDepth(TreeNode* root) {
//根节点高度为二叉树最大深度
return getHeight(root);
}
};
111.二叉树的最小深度
左右孩子都为空的节点才是叶子节点
class Solution {
public:
int getDepth(TreeNode* root){
if(root == nullptr) return 0;
int leftdepth = getDepth(root->left);
int rightdepth = getDepth(root->right);
if(root->left==nullptr&&root->right!=nullptr){
return 1+rightdepth;
}
if(root->left!=nullptr&&root->right==nullptr){
return 1+leftdepth;
}
int result = 1 + min(leftdepth,rightdepth);
return result;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};