LeetCode 226 Invert Binary Tree(转换二叉树)

时间:2022-08-04 07:40:27

翻译

将下图中上面的二叉树转换为以下的形式。详细为每一个左孩子节点和右孩子节点互换位置。

LeetCode 226 Invert Binary Tree(转换二叉树)

原文

如上图

分析

每次关于树的题目出错都在于边界条件上……所以这次细致多想了一遍:

void swapNode(TreeNode* tree) {
if (tree == NULL || (tree->left == NULL && tree->right == NULL)) {}
else if (tree->left == NULL && tree->right != NULL) {
TreeNode* temp = tree->right;
tree->left = temp;
tree->right = nullptr;
}
else if (tree->right == NULL && tree->left != NULL) {
TreeNode* temp = tree->left;
tree->right = temp;
tree->left = nullptr;
}
else {
TreeNode* temp = tree->left;
tree->left = tree->right;
tree->right = temp;
}
}

不过这样还不够,它不过互换了一次。所以我们要用到递归:

if(tree->left != NULL)
swapNode(tree->left);
if(tree->right != NULL)
swapNode(tree->right);

最后在题目给定的函数内部调用自己写的这个递归函数就好。

TreeNode* invertTree(TreeNode* root) {
if (root == NULL) return NULL;
swapNode(root);
return root;
}

代码

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void swapNode(TreeNode* tree) {
if (tree == NULL || (tree->left == NULL && tree->right == NULL)) {}
else if (tree->left == NULL && tree->right != NULL) {
TreeNode* temp = tree->right;
tree->left = temp;
tree->right = nullptr;
}
else if (tree->right == NULL && tree->left != NULL) {
TreeNode* temp = tree->left;
tree->right = temp;
tree->left = nullptr;
}
else {
TreeNode* temp = tree->left;
tree->left = tree->right;
tree->right = temp;
}
if (tree->left != NULL)
swapNode(tree->left);
if (tree->right != NULL)
swapNode(tree->right);
} TreeNode* invertTree(TreeNode* root) {
if (root == NULL) return NULL;
swapNode(root);
return root;
}
};

学习

自己的解决方式还是太0基础,所以来学习学习大神的解法:

TreeNode* invertTree(TreeNode* root) {

    if(nullptr == root) return root;

    queue<TreeNode*> myQueue;   // our queue to do BFS
myQueue.push(root); // push very first item - root while(!myQueue.empty()){ // run until there are nodes in the queue
TreeNode *node = myQueue.front(); // get element from queue
myQueue.pop(); // remove element from queue if(node->left != nullptr){ // add left kid to the queue if it exists
myQueue.push(node->left);
}
if(node->right != nullptr){ // add right kid
myQueue.push(node->right);
} // invert left and right pointers
TreeNode* tmp = node->left;
node->left = node->right;
node->right = tmp; }
return root;
}

争取以后少用递归了。加油!