《leetCode》:Flatten Binary Tree to Linked List

题目

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
        / \
       2   5
      / \   \
     3   4   6
The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
click to show hints.

Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

思路

思路:先求出此二叉树的前序遍历,然后进行构建

实现代码如下:

/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
#define N 100000 //要足够大
void getPreOrder(struct TreeNode* root,int *treeNodePreOrder,int* index){
    if(root==NULL){
        return;
    }
    treeNodePreOrder[(*index)]=root->val;
    (*index)++;
    getPreOrder(root->left,treeNodePreOrder,index);
    getPreOrder(root->right,treeNodePreOrder,index);    
}
void flatten(struct TreeNode* root) {
    if(root==NULL){
        return;
    }
    //第一步:求出二叉树的前序遍历
    int treeNodePreOrder[N];   
    int index=0;
    getPreOrder(root,treeNodePreOrder,&index); 
    //第二步:进行构建
    struct TreeNode* cur=root;
    cur->left=NULL;
    for(int i=1;i<index;i++){
        struct TreeNode *node=(struct TreeNode *)malloc(sizeof(struct TreeNode));
        if(node==NULL){
            exit(EXIT_FAILURE);
        }
        node->val=treeNodePreOrder[i];
        node->left=NULL;
        node->right=NULL;
        cur->right=node;
        cur=cur->right;
    } 
}

上面是先求出了二叉树的先序遍历中各个节点的value,然后进行了构建。

想着可不可以直接保存各个节点的指针,然后进行构建,于是就有了如下的代码,本想着这样会给代码带来效率上的优化,但是,从AC结果来看却没有带来优化。

实现代码如下:

#define N 100000
void getPreOrder(struct TreeNode* root,struct TreeNode **treeNodePreOrder,int* index){
    if(root==NULL){
        return;
    }
    treeNodePreOrder[(*index)]=root;
    (*index)++;
    getPreOrder(root->left,treeNodePreOrder,index);
    getPreOrder(root->right,treeNodePreOrder,index);    
}
void flatten(struct TreeNode* root) {
    //第一步:求出二叉树的前序遍历
    struct TreeNode** treeNodePreOrder=( struct TreeNode** )malloc(N*sizeof(struct TreeNode *));
    if(treeNodePreOrder==NULL){
        exit(EXIT_FAILURE);
    }   
    int index=0;

    getPreOrder(root,treeNodePreOrder,&index); 
    //第二步:进行构建
    struct TreeNode* cur=root;

    for(int i=1;i<index;i++){
        cur->right=treeNodePreOrder[i];
        cur->left=NULL;//这里是需要注意的
        cur=cur->right;
    } 
}

你可能感兴趣的:(LeetCode,LinkedList,flatten,BinaryTree)