递归
/**
* 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) {
if (!root) return root;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
迭代
/**
* 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) {
if (!root) return root;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* node;
node = st.top();
st.pop();
if (node) {
//st.pop();
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
st.push(node);
st.push(NULL);
}
else {
// st.pop();
node = st.top();
st.pop();
swap(node->left, node->right);
}
}
return root;
}
};

分析
- 使用了前序遍历
- 不能使用中序遍历,因为中序遍历会把某些节点的左右孩子翻转了两次
本文探讨了两种方法来反转二叉树:递归和迭代。递归采用前序遍历策略,而迭代则通过栈操作避免重复翻转。两种方法对比,展示了编程的不同技巧应用。
669

被折叠的 条评论
为什么被折叠?



