Leetcode 114 Solution
This article provides solution to leetcode question 114 (flatten-binary-tree-to-linked-list)
Access this page by simply typing in "lcs 114" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/flatten-binary-tree-to-linked-list
Solution
/**
* 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*& head, TreeNode*& tail)
{
if (root == NULL)
{
head = NULL;
tail = NULL;
return;
}
TreeNode *left_head, *left_tail, *right_head, *right_tail;
flatten(root->left, left_head, left_tail);
flatten(root->right, right_head, right_tail);
head = root;
TreeNode* curr = root;
curr->left = NULL;
if (left_head)
{
curr->right = left_head;
curr = left_tail;
}
if (right_head)
{
curr->right = right_head;
curr = right_tail;
}
tail = curr;
}
void flatten(TreeNode* root) {
TreeNode *head, *tail;
flatten(root, head, tail);
}
};