要求
- 时间限制:1秒
- 空间限制:32768K
- 热度指数:214565
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
思路
思路一:递归
递归的思路主要是利用了二叉树的前序遍历。
python实现
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
temp = TreeNode(0)
def Mirror(self, root):
# write code here
if root is None:
return root
temp = root.right
root.right = root.left
root.left = temp
self.Mirror(root.left)
self.Mirror(root.right)
return root
- 运行时间:23ms
- 占用内存:5728k
C++实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode *temp;
void Mirror(TreeNode *pRoot) {
if (pRoot == NULL)
return;
temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
};
- 运行时间:5ms
- 占用内存:588k
思路二:栈的非递归
python实现
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if root is None:
return root
temp = TreeNode(0)
cur = temp
stack = []
stack.append(root)
while (len(stack)):
cur = stack[-1]
stack.pop()
temp = cur.right
cur.right = cur.left
cur.left = temp
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
return root
- 运行时间:24ms
- 占用内存:5740k
C++实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode *temp;
void Mirror(TreeNode *pRoot) {
if (pRoot == NULL)
return;
TreeNode *p = NULL;
stack<TreeNode *> st;
st.push(pRoot);
while (st.size()){
p = st.top();
st.pop();
swap(p->left, p->right);
if (p->left) st.push(p->left);
if (p->right) st.push(p->right);
}
}
};
- 运行时间:3ms
- 占用内存:460k
思路三:队列的非递归方法
C++实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
TreeNode *temp;
void Mirror(TreeNode *pRoot) {
if (pRoot == NULL)
return;
TreeNode *p = NULL;
queue<TreeNode *> qu;
qu.push(pRoot);
while (qu.size()){
p = qu.front();
qu.pop();
swap(p->left, p->right);
if (p->left) qu.push(p->left);
if (p->right) qu.push(p->right);
}
}
};
- 运行时间:5ms
- 占用内存:460k