226.翻转二叉树
题解
//基于层序遍历的迭代法
TreeNode* invertTree_(TreeNode* root) {
queue<TreeNode*> que;
if (root == nullptr) return root;
que.push(root);
while (!que.empty()) {
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;
}
//基于先序遍历的递归法
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return root;
invertTree(root->left);
invertTree(root->right);
return root;
}
总结
采用一种遍历方式,对遍历到的结点交换左右指针。
101.对称二叉树
题解
bool compare(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;
bool outside = compare(left->left, right->right);
bool inside = compare(left->right, right->left);
return outside && inside;
}
bool isSymmetric(TreeNode* root) {
if (!root) return true;
return compare(root->left, root->right);
}
总结
递归时,同时传递根节点的左孩子和根节点的右孩子。
104.二叉树最大深度
题解
int maxDepth(TreeNode* root) {
if (!root) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
int dep = left >= right ? left + 1 : right + 1;
return dep;
}
111.二叉树最小深度
题解
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
if (!left && right) return right + 1;
else if (left && !right) return left + 1;
else return min(left, right) + 1;
}