Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9to
4 / \ 7 2 / \ / \ 9 6 3 1
这道题的就是我们常见的求二叉树的镜像,对于二叉树这种问题,第一直觉还是递归。
1.递归(DFS)
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL)
return NULL;
invert_tree_detail(root);
return root;
}
private:
void invert_tree_detail(TreeNode*& t){
if(t->left == NULL && t->right == NULL)
return ;
if(t->left != NULL)
invert_tree_detail(t->left); //第一次在这里错写成了t=t->left,我还纳闷为什么没改变,唉~
if(t->right != NULL)
invert_tree_detail(t->right);
std::swap(t->left, t->right);
}
};
2.非递归,我当时想到了二叉树后序遍历,这个方法确实可以实现,但是较为复杂,其实呢它就是上面版本的非递归实现。(DFS)
利用一个对组,保存是从左右子树哪个回退的标记。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL)
return NULL;
invert_tree_detail(root);
return root;
}
private:
typedef enum {L, R}FLAG;
void invert_tree_detail(TreeNode*& t){
std::pair<TreeNode*, FLAG> pr(t, L);
std::stack<pair<TreeNode*, FLAG> > st;
st.push(pr);
do{
TreeNode* tmp = st.top().first;
FLAG flag = st.top().second;
st.pop();
if(flag == L){
st.push(std::make_pair(tmp, R));
if(tmp->right != NULL)
st.push(std::make_pair(tmp->right, L));
if(tmp->left != NULL)
st.push(std::make_pair(tmp->left, L));
}
else{
std::swap(tmp->left, tmp->right);
}
}while(!st.empty());
}
};3.别人的递归方法,比我的简练,它是直接以第三方交换的方式递归,真的很不错(DFS)
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL)
return root;
TreeNode* tmp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(tmp);
return root;
}
};4.迭代法
这个方法我绝壁没有想到,我只是想先深入下去交换最底层的子树,然后由下至上。而这个是迭代法,利用stack进行回溯。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL)
return root;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* tmp = st.top();
st.pop();
if(tmp != NULL){
st.push(tmp->left);
st.push(tmp->right);
std::swap(tmp->left, tmp->right);
}
}
return root;
}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == NULL)
return NULL;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
TreeNode* iter = que.front();
que.pop();
std::swap(iter->left, iter->right);
if(iter->left != NULL)
que.push(iter->left);
if(iter->right != NULL)
que.push(iter->right);
}
return root;
}
};
5838



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



