【代码随想录day 14】 力扣 226.反转二叉树
视频讲解:https://www.bilibili.com/video/BV1sP4y1f7q7/?vd_source=a935eaede74a204ec74fd041b917810c
文档讲解:https://programmercarl.com/0226.%E7%BF%BB%E8%BD%AC%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC
力扣题目:https://leetcode.cn/problems/invert-binary-tree/submissions/650770871/
这道题的主要思路就是从根节点像下出发,两两反转节点,用递归方法即可,定义一个临时节点来交换左节点和右节点,再继续递归,如果节点为空则返回空。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++代码与其思想一样,写法上略有不同:
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;}
};