视频讲解:https://www.bilibili.com/video/BV1sP4y1f7q7/?vd_source=a935eaede74a204ec74fd041b917810c
文档讲解:https://programmercarl.com/0226.翻转二叉树.html#其他语言版本
力扣题目:https://leetcode.cn/problems/invert-binary-tree/submissions/650770871/
这道题的主要思路就是从根节点像下出发,两两反转节点,用递归方法即可,定义一个临时节点来交换左节点和右节点,再继续递归,如果节点为空则返回空。C代码如下所示:
这里用的是前序遍历,用后序遍历也可以,将交换部分放在迭代之后即可,但中序遍历不行,中序遍历再遍历前就进行过一次反转,所以再遍历后要进行同样一次反转。
c
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root) {
//如果根节点为空,不用管直接返回
if(!root)
{
return NULL;
}
//根节点不为空,交换左右子树
struct TreeNode *tmp=root->right;
root->right=root->left;
root->left=tmp;
//递归调用自身继续反转
invertTree(root->left);
invertTree(root->right);
return root;
}
C++代码与其思想一样,写法上略有不同:
cpp
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == NULL) return root;
swap(root->left, root->right); // 中
invertTree(root->left); // 左
invertTree(root->right); // 右
return root;
}
};