这里推荐层次遍历、模板写法(不好理解,但其实好套用)
层次遍历写法
/**层次遍历的方式:翻转二叉树
* 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*> que;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0; i<size; i++){
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;
}
};
模板写法:
/**模板写法1
*前序遍历:中 左 右
*入栈:右 左 中
* 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;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode *node = st.top();
if(node != nullptr){
st.pop();
if(node->right) st.push(node->right); //这样保证栈中的空指针只有当作为标志的空指针,
if(node->left) st.push(node->left); //而不是左右节点中存在空指针
st.push(node);
st.push(nullptr);
}else{
st.pop();
node = st.top();
st.pop();
swap(node->left, node->right);
}
}
return root;
}
};
/**模板写法2
*后序遍历: 左 右 中
*入栈: 中 右 左
* 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;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode *node = st.top();
if(node != nullptr){
st.pop();
st.push(node);
st.push(nullptr);
if(node->right) st.push(node->right); //这样保证栈中的空指针只有当作为标志的空指针,
if(node->left) st.push(node->left); //而不是左右节点中存在空指针
}else{
st.pop();
node = st.top();
st.pop();
swap(node->left, node->right);
}
}
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;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode *node = st.top();
if(node != nullptr){
st.pop();
if(node->right) st.push(node->right); //这样保证栈中的空指针只有当作为标志的空指针,
st.push(node);
st.push(nullptr);
if(node->left) st.push(node->left); //而不是左右节点中存在空指针
}else{
st.pop();
node = st.top();
st.pop();
swap(node->left, node->right);
}
}
return root;
}
};