https://leetcode.cn/problems/invert-binary-tree/submissions/
Our idea for this topic is actually very simple. When encountering a null pointer, we have to return a null pointer because it needs to be exchanged. But there is a small detail here, that is, we save its left and right nodes. Our function interface here has a return value. , we save the currently returned recursive left tree or right tree. At this time, the root is their parent node for exchange. Let’s look at the code.
struct TreeNode* invertTree(struct TreeNode* root) {
if(root == NULL)
{
return NULL;
}
struct TreeNode* left = invertTree(root->left);
struct TreeNode* right = invertTree(root->right);
root->left = right;
root->right = left;
return root;
}
Let's see what a recursively expanded graph looks like.
You may have a better understanding by looking at this picture. Here we have also drawn the nodes that store positions 1 and 3 and exchanged them. You can also try to draw them. This is what we will share today.