【LeetCode】114. Flatten Binary Tree to Linked List

114. Flatten Binary Tree to Linked List

Description:
Given a binary tree, flatten it to a linked list in-place.
Difficulty:Medium
Example:

    1
   / \
  2   5
 / \   \
3   4   6

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

方法:in place

  • Time complexity : O ( n ) O\left ( n \right ) O(n)
  • Space complexity : O ( 1 ) O\left ( 1 \right ) O(1)
    思路:
    先把right放在left的最右侧,再把left放在right,清空left,枚举root = root->right
class Solution {
public:
    void flatten(TreeNode* root) {
        while(root){
            if(root->left){
                TreeNode * p = root->left;
                while(p->right)
                    p = p->right;
                p->right = root->right;
                root->right = root->left;
                root->left = NULL;
            }
            root = root->right;
        }
    }
};
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页