前言
翻转二叉树是一种简单的二叉树问题,下面我们分别从递归和迭代的角度解决它。
可以完成leetcode上的
226.翻转二叉树
一、递归
前序遍历
依据 中-左-右 的顺序,我们先从根节点开始,交换left和right,在用递归的方法分别翻转左子树和右子树,完成整个二叉树的翻转。
代码如下:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL) return NULL;
// TreeNode* tem =root->left;
// root->left =root->right;
// root->right= tem;
swap(root->left,root->right);//直接使用函数
invertTree(root->left);
invertTree (root->right);
return root;
}
};
层序遍历
按照二叉树的深度进行遍历,对每一个节点的left和right指针进行交换,直到叶节点再返回,递归交换所有节点的左右指针,完成对二叉树的翻转。
class Solution {
public:
void order(TreeNode*cur ,int depth){
if(cur==NULL) return ;
swap(cur->left,cur->right);
order(cur->left,depth+1);
order(cur->right,depth+1);
}
TreeNode* invertTree(TreeNode* root) {
int depth =0;
order(root,depth);
return root;
}
};
二、迭代
能递归就一定可以迭代,我们再使用迭代法尝试完成此题。
前序遍历
与遍历不同的是,当弹出栈顶后,我们将它的左右指针交换位置,再将指针分别存入栈中,依次完成所有指针的交换,进而翻转二叉树。
代码如下:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL) return root;
stack<TreeNode*> st;
st.emplace(root);
while(!st.empty()){
TreeNode*cur=st.top();
st.pop();
swap(cur->left,cur->right);
if(cur->right) st.emplace(cur->right);
if(cur->left) st.emplace(cur->left);
}
return root;
}
};
层序遍历
与前序一样,在弹出队列首元素后它的左右指针交换位置。
代码如下:
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL) return root;
queue <TreeNode*> que;
que.emplace(root);
while(!que.empty()){
int size=que.size();
for(int i=0;i<size;i++){
TreeNode*cur=que.front();
que.pop();
swap(cur->left,cur->right);
if(cur->left) que.emplace(cur->left);
if(cur->right) que.emplace(cur->right);
}
}
return root;
}
};