将每个结点的左右子树进行交换
- 递归法
- 前序
中序:会将某些结点的左右子树翻转两次- 后序
- 层序
- 迭代法
- 前序
- 中序:避免了递归法的翻转多次情况,因为迭代法是靠栈来遍历,而不是靠指针来遍历,是先将当前结点的左右子结点存储在栈中,翻转后不会改变栈中左右子树的先后顺序
- 后序
- 层序
递归法
前序遍历
// 1 确定递归函数的参数和返回值TreeNode *invertTree(TreeNode *root) {// 2 确定递归终止的条件if (root == NULL) return root;// 3 确定单层递归的逻辑swap(root->left, root->right); // 中invertTree(root->left); // 左invertTree(root->right); // 右return root;}
中序遍历 - 改进
TreeNode *invertTree(TreeNode *root) {// 2 确定递归终止的条件if (root == NULL) return root;// 3 确定单层递归的逻辑invertTree(root->left); // 左swap(root->left, root->right); // 中-翻转invertTree(root->left); // 左return root;}
迭代法
模拟深度优先遍历
前序遍历
TreeNode *invertTree(TreeNode *root) {if (root == NULL) return NULL;stack<TreeNode *> st;st.push(root);while (!st.empty()) {TreeNode *cur = st.top(); // 中st.pop();swap(cur->left, cur->right);if (cur->right) st.push(cur->right); // 右if (cur->left) st.push(cur->left); // 左}return root;}
中序遍历 - 标记法
TreeNode *invertTree(TreeNode *root) {if (root == NULL) return NULL;stack<TreeNode *> st;st.push(root);while (!st.empty()) {TreeNode *cur = st.top();st.pop();if (cur != NULL) {if (cur->right) st.push(cur->right); // 右st.push(cur); // 中st.push(NULL);// 不在这翻转if (cur->left) st.push(cur->left); // 左} else {cur = st.top();st.pop();swap(cur->left, cur->right); // 结点处理逻辑}}return root;}
模拟广度优先遍历
- 层序遍历
TreeNode *invertTree(TreeNode *root) { if (root == NULL) return root; queue<TreeNode *> q; q.push(root); while (!q.empty()) { TreeNode *cur = q.front(); q.pop(); swap(cur->left, cur->right); if (cur->left) q.push(cur->left); if (cur->right) q.push(cur->right); } return root; }
