题目:
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
AC代码
void flatten(struct TreeNode* root){
if(root != NULL){
struct TreeNode* res = (struct TreeNode*)malloc(sizeof(struct TreeNode));
res->val = -1;
struct TreeNode* p1 = res;
struct TreeNode* stack[10010];
int index = -1;
stack[++index] = root;
while(index >= 0){
struct TreeNode* temp = (struct TreeNode*)malloc(sizeof(struct TreeNode));
temp = stack[index--];
if(temp->right){
stack[++index] = temp->right;
}
if(temp->left){
stack[++index] = temp->left;
}
p1->left = NULL;
p1->right = temp;
p1 = p1->right;
}
p1->left = NULL;
p1->right = NULL;
root = res->right;
}
}
来源:CSDN
作者:liuliuliudy
链接:https://blog.csdn.net/qq_33607393/article/details/104738424