Skip to content

Latest commit

 

History

History
126 lines (115 loc) · 2.62 KB

114. Flatten Binary Tree to Linked List.md

File metadata and controls

126 lines (115 loc) · 2.62 KB

114. 二叉树展开为链表

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

例如,给定二叉树

    1
   / \
  2   5
 / \   \
3   4   6

将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

解法一:

//时间复杂度O(n), 空间复杂度O(n)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root, TreeNode* r_chd) {
        if(!root->left && !root->right) {
            root->right = r_chd;
            return;
        }
        
        if(root->right) flatten(root->right, r_chd);
        else root->right = r_chd;
        
        if(root->left) {
            flatten(root->left, root->right);
            root->right = root->left;
            root->left = nullptr;
        }
    }
    void flatten(TreeNode* root) {
        if(!root) return;
        flatten(root, nullptr);
    }
};

解法二:

//时间复杂度O(n), 空间复杂度O(n)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        if(!root) return;
        flatten(root->right);
        flatten(root->left);
        root->right = last;
        root->left = nullptr;
        last = root;
    }
private:
    TreeNode* last = nullptr;
};

解法三:

//时间复杂度O(?), 空间复杂度O(n)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        if(!root) return;
        flatten(root->left);
        flatten(root->right);
        
        TreeNode* temp = root->right;
        root->right = root->left;
        root->left = nullptr;
        while(root->right) root = root->right;
        root->right = temp;
    }
};

解法一:

把右子树展开,然后再把左子树展开后加入到右子树之上。解法一和解法二思路类似。

解法三:

递归法,后序遍历。先左或先右都可以。

2019/11/22 11:30