leetcode 226 反转二叉树
翻转一棵二叉树。
示例:
输入:
4
/
2 7
/ \ /
1 3 6 9
输出:
4
/
7 2
/ \ /
9 6 3 1
五种方式实现二叉树的反转
遍历的过程中对只访问一次节点的方式都可以,中序遍历节点反转了两次不能用
前序递归
递归函数的返回值:二叉树的根节点
递归函数的参数:二叉树的当前节点
递归函数的函数体:当前节点不为空则互换它的左右子树,反转左子树,反转右子树
递归函数的终止添加:当前节点为空则退出当前递归
* 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) {}
* };
*
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr)
return root;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
前序迭代
TreeNode* invertTree(TreeNode* root) {
TreeNode* cur = root;
stack<TreeNode*> sta;
while(!sta.empty() || cur){
if(cur){
sta.push(cur);
swap(cur->left, cur->right);
cur = cur->left;
continue;
}
cur = sta.top()->right;
sta.pop();
}
return root;
}
后序递归
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr)
return root;
invertTree(root->left);
invertTree(root->right);
swap(root->left, root->right);
return root;
}
后序迭代
TreeNode* invertTree(TreeNode* root) {
TreeNode* cur = root;
stack<TreeNode*> sta;
while(!sta.empty() || cur){
if(cur){
sta.push(cur);
swap(cur->left, cur->right);
cur = cur->right;
continue;
}
cur = sta.top()->left;
sta.pop();
}
return root;
}
层序反转
TreeNode* invertTree(TreeNode* root) {
TreeNode* cur = root;
queue<TreeNode*> que;
if(cur)
que.push(cur);
while(!que.empty()){
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;
}