Leetcode:114. 二叉树展开为链表

橙三吉。 提交于 2020-03-08 21:17:00

题目:

给定一个二叉树,原地将它展开为链表。

例如,给定二叉树

    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;
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!