226. 翻转二叉树
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例:
题目链接:LeetCode226.翻转二叉树
文档讲解:代码随想录LeetCode226.翻转二叉树
题解
递归法
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;
}
};
迭代法:深度优先遍历(前序遍历)
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
stack<TreeNode*> stk;
if (root == nullptr)
return root;
else
stk.push(root);
while (!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
swap(node->left, node->right);
if (node->right)
stk.push(node->right);
if (node->left)
stk.push(node->left);
}
return root;
}
};
迭代法:广度优先遍历
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode*> que;
if (root == nullptr)
return root;
else
que.push(root);
while (!que.empty()) {
int n = que.size();
for (int i = 0; i < n; 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. 对称二叉树
给你一个二叉树的根节点 root , 检查它是否轴对称。
示例:
题目链接:LeetCode101.对称二叉树
文档讲解:代码随想录LeetCode101.对称二叉树
题解
递归法
class Solution {
public:
bool compare(TreeNode* p, TreeNode* q) {
if (!p && !q)
return true;
if (!p || !q)
return false;
if (p->val != q->val)
return false;
return (compare(p->left, q->right) && compare(p->right, q->left));
}
bool isSymmetric(TreeNode* root) {
if (root == nullptr)
return true;
return compare(root->left, root->right);
}
};
迭代法:使用队列
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == nullptr)
return true;
queue<TreeNode*> que;
que.push(root->left);
que.push(root->right);
while (!que.empty()) {
TreeNode* leftNode = que.front();
que.pop();
TreeNode* rightNode = que.front();
que.pop();
if (!leftNode && !rightNode)
continue;
if (!leftNode || !rightNode)
return false;
if (leftNode->val != rightNode->val)
return false;
que.push(leftNode->left);
que.push(rightNode->right);
que.push(leftNode->right);
que.push(rightNode->left);
}
return true;
}
};
104. 二叉树的最大深度
给定一个二叉树 root ,返回其最大深度。
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
题解
递归法
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr)
return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
迭代法见Day13层序遍历第8题
111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
题解
递归法
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root)
return 0;
if (!root->left && root->right)
return minDepth(root->right) + 1;
if (root->left && !root->right)
return minDepth(root->left) + 1;
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};
迭代法见Day13层序遍历第9题