← Home

114. Flatten Binary Tree to Linked List

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
114

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 114. Flatten Binary Tree to Linked List, the solution in this repository is mainly a two pointers solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are preorder, flatten.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 4 ms, faster than 97.16% of C++ online submissions for Flatten Binary Tree to Linked List.
02//Memory Usage: 13.3 MB, less than 59.25% of C++ online submissions for Flatten Binary Tree to Linked List.
03/**
04 * Definition for a binary tree node.
05 * struct TreeNode {
06 *     int val;
07 *     TreeNode *left;
08 *     TreeNode *right;
09 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
10 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
12 * };
13 */
14class Solution {
15public:
16    void preorder(TreeNode* node, vector<TreeNode*>& nodes){
17        if(!node) return;
18        
19        nodes.push_back(node);
20        preorder(node->left, nodes);
21        preorder(node->right, nodes);
22    }
23    
24    void flatten(TreeNode* root) {
25        vector<TreeNode*> nodes;
26        preorder(root, nodes);
27        
28        // cout << "nodes: " << nodes.size() << endl;
29        
30        for(int i = 0; i+1 < nodes.size(); ++i){
31            nodes[i]->left = nullptr;
32            nodes[i]->right = nodes[i+1];
33        }
34    }
35};
36
37//post order traversal
38//https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/36977/My-short-post-order-traversal-Java-solution-for-share
39//Runtime: 12 ms, faster than 31.00% of C++ online submissions for Flatten Binary Tree to Linked List.
40//Memory Usage: 12.9 MB, less than 59.25% of C++ online submissions for Flatten Binary Tree to Linked List.
41class Solution {
42public:
43    TreeNode* prev;
44    
45    void flatten(TreeNode* root) {
46        if(!root) return;
47        //post-order traversal
48        //visit right child -> left child -> itself
49        flatten(root->right);
50        flatten(root->left);
51        //prev will be its successor in in-order traversal!
52        root->right = prev;
53        root->left = nullptr;
54        prev = root;
55    }
56};
57
58//iterative
59//https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/37010/Share-my-simple-NON-recursive-solution-O(1)-space-complexity!
60//Runtime: 4 ms, faster than 97.16% of C++ online submissions for Flatten Binary Tree to Linked List.
61//Memory Usage: 13 MB, less than 59.25% of C++ online submissions for Flatten Binary Tree to Linked List.
62class Solution {
63public:
64    void flatten(TreeNode* root) {
65        TreeNode* cur = root;
66        
67        while(cur){
68            if(cur->left){
69                TreeNode* prev = cur->left;
70                
71                while(prev->right) prev = prev->right;
72                //now prev is cur's predecessor in in-order traversal
73                //it's also rightmost node of cur's left subtree
74                
75                //let cur's right subtree be cur's left subtree's descendants
76                //prev->right must be nullptr, so this op is safe
77                prev->right = cur->right;
78                //move cur's left subtree to the right
79                cur->right = cur->left;
80                //the reconstructed tree don't have left children
81                cur->left = nullptr;
82            }
83            
84            //move forward in the reconstructed tree
85            cur = cur->right;
86        }
87    }
88};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.