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

思路:

思路1:本质上是一个二叉树的前序遍历,利用非递归的方法可以很方便得到结果。 思路2:根据留言的建议,递归的实现如下。

代码:

思路1

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        TreeNode * stack[100];
        int top = 0;
        
        TreeNode * pre = NULL;
        if(root == NULL)
        {
            return;
        }
        else
        {
            stack[top++] = root;
        }
        
        while(top > 0)
        {
            TreeNode * p = stack[--top];
            if(p->right != NULL)
            {
                stack[top++] = p->right;
            }
            if(p->left != NULL)
            {
                stack[top++] = p->left;
            }
            p->left = NULL;
            if(pre != NULL)
            {
                pre->right = p;
            }
            p->right = NULL;
            pre = p;
        };
    }
};

思路2

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        flatTree(root);
    }
    
    TreeNode * flatTree(TreeNode *root)
    {
        if(root == NULL)
        {
            return NULL;
        }
        else if(root->left ==NULL && root->right == NULL)
        {
            return root;
        }
        else
        {
            TreeNode * left = root->left;
            TreeNode * right = root->right;
            root->left = NULL;
            if(left!=NULL)
            {
                root->right = left;
                TreeNode * tmp = flatTree(left);
                tmp->left = NULL;
                if(right==NULL)
                {
                    return tmp;
                }
                else
                {
                    tmp->right = right;
                }
            }
            return flatTree(right);
        }
    }
};

    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11833621
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞