226.翻转二叉树
要点:只要能理解到,翻转二叉树,其实就是把二叉树中的所有节点的左右孩子交换,这道题就很简单了。所有对二叉树的遍历方法,即只要能访问二叉树所有节点,访问的同时交换其左右孩子,这样的方法都适用于这道题目。
/** 递归翻转二叉树 */
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr)
return root;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
101.对称二叉树
要点:即比较左子树和右子树是不是对称的,或者说左子树是不是右子树的翻转,几种情况,左空右有、左有右空、左空有空、左右都有(判断值相等),判断是否对称,那就是比较左的左和右的右是否对称,以及左的右和右的左是否对称,用递归写出代码如下。
class Solution {
public:
bool compare(TreeNode* left, TreeNode* right) {
if (left == nullptr && right != nullptr)
return false;
else if (left == nullptr && right == nullptr)
return true;
else if (left != nullptr && right == nullptr)
return false;
else if (left->val != right->val)
return false;
bool outside = compare(left->left, right->right);
bool inside = compare(left->right, right->left);
return outside && inside;
}
bool isSymmetric(TreeNode* root) {
if (root == nullptr)
return true;
return compare(root->left, root->right);
}
};
104.二叉树的最大深度
要点:最大深度,就是根节点的最大高度。层序遍历一层层往下+1,理解起来容易一点,递归的话,求深度用前序,求高度用后序,这题前序后序都可以,不过后序遍历的代码精简,且理解起来容易
class Solution {
public:
int getHeight(TreeNode* node) {
if (node == nullptr)
return 0;
int leftHeight = getHeight(node->left);
int rightHeight = getHeight(node->right);
int maxHeight = 1 + max(leftHeight, rightHeight);
return maxHeight;
}
int maxDepth(TreeNode* root) { return getHeight(root); }
};
111.二叉树的最小深度
要点:层序遍历全杀了。用递归的话,也是后序遍历,与求最大深度不同地方就是,当左右子节点为空时的处理方式,当左右子节点有一个为空时,它的深度并不为0,而是非空子节点深度+1
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == nullptr)
return 0;
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
if (node->left == nullptr && node->right != nullptr) {
return 1 + rightDepth;
}
if (node->left != nullptr && node->right == nullptr) {
return 1 + leftDepth;
}
return 1 + min(leftDepth, rightDepth);
}
int minDepth(TreeNode* root) { return getDepth(root); }
};

被折叠的 条评论
为什么被折叠?



