• 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.

    刚开始想偷懒想把几个条件混着写,但是写了半天没写出来。后来把4种分开写,很快就完成通过了。注意不是由树变链。

    /**
     * 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) {
            flat(root);
        }
        TreeNode * flat(TreeNode *root)
        {
            TreeNode *tail = root;
            TreeNode * l = root;
            TreeNode * r = root;
            if(root == NULL)return NULL;
            if(root->left == NULL && root->right == NULL)return root;
            if(root->left != NULL && root->right == NULL)
            {
                l= flat(root->left);
                root->right = root->left;
                root->left = NULL;
                return l;
            }
            else if(root->right!= NULL&&root->left == NULL)
            {
                r = flat(root->right);
                return r;
            }
            else
            {
                r = flat(root->right);
                l= flat(root->left);
                l->right = root->right;
                root->right= root->left;
                root->left =NULL;
                return r;
            }
        }
    };
    

      

  • 相关阅读:
    POJ1064 浮点数二分答案
    2019牛客暑期多校训练营(第二场)H.Second Large Rectangle
    最大全1子矩阵的两种解法(例题:City Game HDU
    POJ
    Codeforces Round #588 (Div. 2) C
    1216E
    1221D
    BUY LOW, BUY LOWER, POJ
    Priest John's Busiest Day (2-sat)
    poj1080
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3611529.html
Copyright © 2020-2023  润新知