目录
一、层序遍历
实现思想:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val):val(val),left(nullptr),right(nullptr){}
};
void add(TreeNode* &root, int val){
if (!root) root = new TreeNode(val);
if (root->val < val) add(root->right, val);
else if (root->val > val) add(root->left, val);
else return;
}
void create(TreeNode* &root){
for (int i = 0; i < 10; i++){
add(root, i);
}
}
void mid(TreeNode* root){
if (!root) return;
mid(root->left);
cout << root->val<< ' ';
mid(root->right);
}
void cengci(TreeNode *root){
queue<TreeNode*> que;
//如果树存在就将它的根节点入队
if (root != nullptr) que.push(root);
//用来存储结果的二维数组
vector<vector<int>> result;
while(!que.empty()){
//每一次存储树一层上结点的数量
int size = que.size();
//存放每一层上的结点的值
vector<int> vec;
//将一层上的每一个结点都检查它的左右孩子,如果存在则将左右孩子也入队
while(size--) {
TreeNode* tmp = que.front();que.pop();
vec.push_back(tmp->val);
if (tmp->left) que.push(tmp->left);
if (tmp->right) que.push(tmp->right);
}
result.push_back(vec);
}
for (int i = 0; i < result.size(); i++){
for (int j = 0; j < result[i].size(); j++){
cout << result[i][j]<<' ';
}
cout << endl;
}
}
int main(void){
TreeNode* root = new TreeNode(7);
create(root);
cout << "中序遍历结果: "; mid(root);
cout << endl << "层次遍历结果: " << endl;
cengci(root);
}
二、反转二叉树(力扣226)
实现思想:反转二叉树使用先序遍历和后序遍历都可以,但是中序遍历不行,如果要使用中序遍历需要对中序遍历做修改。
class Solution {
public:
void invert(TreeNode* root){
if (!root) return;
swap(root->left, root->right);
invert(root->left);
invert(root->right);
}
TreeNode* invertTree(TreeNode* root) {
invert(root);
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 false;
//左结点为空,右节点为空说明对称
else if (left == nullptr && right == nullptr) return true;
//左结点值不等于右节点值说明不对称
else if (left->val != right->val) return false;
//对比两子树外侧结点是否相等
bool outside = compare(left->left, right->right);
//对比两子树内侧结点是否相等
bool inside = compare(left->right, right->left);
//如果外侧和内侧节点都各自相等的化就说明对称
bool result = outside && inside;
return result;
}
bool isSymmetric(TreeNode* root) {
if (root == nullptr) return false;
return compare(root->left, root->right);
}
};