Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save pdu/4475421 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4475421 to your computer and use it in GitHub Desktop.
Given a binary tree, flatten it to a linked list in-place. http://leetcode.com/onlinejudge
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* flatten_(TreeNode* root) {
if (root->left == NULL && root->right == NULL)
return root;
if (root->left == NULL)
return flatten_(root->right);
if (root->right == NULL) {
TreeNode* tmp = flatten_(root->left);
root->right = root->left;
root->left = NULL;
return tmp;
}
TreeNode* tmp = flatten_(root->left);
tmp->right = root->right;
root->right = root->left;
root->left = NULL;
return flatten_(root->right);
}
void flatten(TreeNode *root) {
if (root == NULL)
return;
flatten_(root);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment