We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4 / 2 7 / \ / 1 3 6 9 镜像输出:
4 / 7 2 / \ / 9 6 3 1
示例 1:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,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* mirrorTree(TreeNode* root) { if (!root) return root; TreeNode* tmp = root->left; root->left = root->right; root->right = tmp; mirrorTree(root->left); mirrorTree(root->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* mirrorTree(TreeNode* root) { if (!root) return root; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* tmp = q.front(); q.pop(); swap(tmp->left, tmp->right); if (tmp->left) q.push(tmp->left); if (tmp->right) q.push(tmp->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* mirrorTree(TreeNode* root) { if (!root) return root; stack<TreeNode*> stk; stk.push(root); while (!stk.empty()) { TreeNode* tmp = stk.top(); stk.pop(); if (tmp) { if (tmp->right) stk.push(tmp->right); if (tmp->left) stk.push(tmp->left); stk.push(tmp); stk.push(nullptr); } else { TreeNode* tmp = stk.top(); stk.pop(); swap(tmp->left, tmp->right); } } return root; } };
本质就是考察树的遍历,模板在这里
The text was updated successfully, but these errors were encountered:
No branches or pull requests
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/
2 7
/ \ /
1 3 6 9
镜像输出:
4
/
7 2
/ \ /
9 6 3 1
示例 1:
限制:
思路很简单,交换一下每个节点的左右指针即可。
解法一:
递归,先序遍历的变形。代码如下:
解法二:
迭代,层序遍历的变形。代码如下:
解法三:
迭代,前序遍历的迭代写法的变形。代码如下:
本质就是考察树的遍历,模板在这里
The text was updated successfully, but these errors were encountered: