我的往期文章:
leetCode 226.翻转二叉树-CSDN博客https://blog.csdn.net/weixin_41987016/article/details/134613347?spm=1001.2014.3001.5501
(一)递归做法(深度)
- C++代码:前序遍历
class Solution {
public:TreeNode* invertTree(TreeNode* root) {if(root==nullptr) return nullptr;swap(root->left,root->right); // 中TreeNode* left = invertTree(root->left); // 左TreeNode* right = invertTree(root->right); // 右return root;}
};
- C++代码:后序遍历
class Solution {
public:TreeNode* invertTree(TreeNode* root) {if(root==nullptr) return nullptr;TreeNode* left = invertTree(root->left); // 左TreeNode* right = invertTree(root->right); // 右swap(root->left,root->right); // 中return root;}
};
- C++代码:中序遍历
class Solution {
public:TreeNode* invertTree(TreeNode* root) {if(root==nullptr) return nullptr;TreeNode* right = invertTree(root->left); // 左swap(root->left,root->right); // 中TreeNode* left = invertTree(root->left); // 左return root;}
};
(二)非递归做法
- C++代码:前序遍历
class Solution {
public:TreeNode* invertTree(TreeNode* root) {if(root == NULL) return root;stack<TreeNode*> st;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;}
};
- C++代码:后序遍历
class Solution {
public:TreeNode* invertTree(TreeNode* root) {if(root == NULL) return root;stack<TreeNode*> st;st.push(root);while(!st.empty()) {TreeNode* node = st.top();st.pop();if(node->right) st.push(node->right); // 右if(node->left) st.push(node->left); // 左 swap(node->left,node->right);}return root;}
};
- C++代码:中序遍历
class Solution {
public:TreeNode* invertTree(TreeNode* root) {if(root == NULL) return root;stack<TreeNode*> st;st.push(root);while(!st.empty()) {TreeNode* node = st.top();st.pop();if(node->left) st.push(node->left); // 左swap(node->left,node->right);if(node->left) st.push(node->left); // 左 }return root;}
};
(三)层序遍历(广度优先遍历)
// 广度优先遍历
class Solution {
public:TreeNode* invertTree(TreeNode* root) {if(root == NULL) return root;queue<TreeNode*> Q;Q.push(root);while(!Q.empty()) {TreeNode* node = Q.front();Q.pop();swap(node->left,node->right); // 节点处理if(node->left) Q.push(node->left); // 左if(node->right) Q.push(node->right); // 右}return root;}
};
参考和推荐文章:
226. 翻转二叉树 - 力扣(LeetCode)https://leetcode.cn/problems/invert-binary-tree/solutions/415494/226-fan-zhuan-er-cha-shu-di-gui-fa-die-dai-fa-xian/