题目链接:https://leetcode-cn.com/problems/invert-binary-tree/
题目描述:
方法一:层序遍历(BFS)
采用层序遍历的方式,每遍历一个节点,就将该节点的左右孩子交换。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode *> que;
if(root != nullptr)
que.push(root);
while(!que.empty())
{
TreeNode *node = que.front();
que.pop();
swap(node->left, node->right); //交换左右孩子
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
return root;
}
};
2.迭代法(前序遍历)DFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
stack<TreeNode*> st;
if(root != nullptr)
st.push(root);
while(!st.empty())
{
TreeNode * node = st.top();
st.pop();
swap(node->left, node->right);
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
}
return root;
}
};
3.递归法
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr)
return root;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};