题目描述:
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
代码:、
方法一、后序遍历递归。
class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL)return;
flatten(root->left);
flatten(root->right);
TreeNode *temp=root->right;
root->right=root->left;
root->left=NULL;
while(root->right)root=root->right;
root->right=temp;
}
};
方法二、非递归
class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL)return;
TreeNode *cur=root;
while(cur){
if(cur->left){
TreeNode *p=cur->left;
while(p->right)p=p->right;
p->right=cur->right;
cur->right=cur->left;
cur->left=NULL;
}
cur=cur->right;
}
}
};
方法三、前序迭代
class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL)return;
stack<TreeNode *>st;
st.push(root);
while(!st.empty()){
TreeNode *t=st.top();st.pop();
if(t->left){
TreeNode *temp=t->left;
while(temp->right)temp=temp->right;
temp->right=t->right;
t->right=t->left;
t->left=NULL;
}
if(t->right)st.push(t->right);
}
}
};
参考:https://www.cnblogs.com/grandyang/p/4293853.html