Skip to content

Instantly share code, notes, and snippets.

@barrysteyn
Last active March 11, 2018 18:01
Show Gist options
  • Select an option

  • Save barrysteyn/5892524 to your computer and use it in GitHub Desktop.

Select an option

Save barrysteyn/5892524 to your computer and use it in GitHub Desktop.
LeetCode: Flatten Binary Tree To Linked List

Flatten Binary Tree to Linked List

http://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list/

Problem Description

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

Structures

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/*
* Time complexity: O(n) (where n is the number of nodes).
* Space: O(1)
*/
class Solution {
public:
TreeNode* flattenT(TreeNode *root) {
if (!root || !root->left && !root->right) return root;
TreeNode *node1 = flattenT(root->left),
*node2 = flattenT(root->right);
if (node1) node1->right = root->right;
if (root->left) root->right = root->left;
root->left = NULL;
return (node2) ? node2 : node1;
}
void flatten(TreeNode *root) {
flattenT(root);
}
};
@apassi99

apassi99 commented Mar 1, 2016

Copy link
Copy Markdown

How's this O(1) space complexity? On each recursive call you are storing 2 variables (node1 and node2) on the stack.

@munkhbat1900

munkhbat1900 commented Mar 11, 2018

Copy link
Copy Markdown

I guess it doesn't store 2 variables on each recursive call, it stores 3 variables, node1, node2 and root.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment