LeetCode 226. Inver Binary Tree 解题报告
题目描述
Invert a binary tree.
示例
4 4
/ \ / \
2 7 to 7 2
/ \ / \ / \ / \
1 3 6 9 9 6 3 1
限制条件
没有明确给出。
解题思路
我的思路:
之前也有提过,二叉树的结构是很适合用递归算法的,所以看到这道题,我的第一个反应就是用递归算法,对于每一棵树,根节点r,左右节点为
其它思路:
除了递归,这道题也能使用BFS(广度优先搜索,Breadth-First-Search)解决。
核心的思想是使用一个队列存储树的节点,初始状态下,队列只有一个根节点。每次从队列中取出一个节点,交换它的左右节点,然后如果它的子节点不为空则将子节点放入到队列中,继续重复之前的过程直到队列为空。此时意味着处理完了所有节点,因此返回原始的根节点。
代码
我的代码
/**
* 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:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) {
return nullptr;
} else {
root->left = invertTree(root->left);
root->right = invertTree(root->right);
TreeNode* tempNode = root->left;
root->left = root->right;
root->right = tempNode;
}
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:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr)
return nullptr;
queue<TreeNode*> myQueue;
myQueue.push(root);
while(!myQueue.empty()) {
TreeNode* current = myQueue.front();
myQueue.pop();
TreeNode* tempNode = current->left;
current->left = current->right;
current->right = tempNode;
if(current->left != nullptr)
myQueue.push(current->left);
if(current->right != nullptr)
myQueue.push(current->right);
}
return root;
}
};
总结
今天这道题复习了一下树的结构,递归的算法还有BFS。对应BFS,我还是运用得很生疏,得自己去找找算法书看看原理,跟多做做题目。
还有那么多坑,慢慢来,加油!