Given the root of a binary tree, flatten the tree into a “linked list”:
Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Input: root = []
Output: []
Input: root = [0]
Output: [0]
From: LeetCode
Link: 114. Flatten Binary Tree to Linked List
Modified Pre-Order Traversal: Traditional pre-order traversal visits a node in the order: root, left subtree, and then right subtree. The modification here is that we’re doing it in a slightly different order: we first flatten the right subtree, then the left subtree, and finally process the current root.
Global prev Variable: This variable keeps track of the last node that we’ve visited. When we visit a new node, we’ll be linking this node to the prev node using the right pointer.
Flattening Process:
Resetting the prev Variable: Before starting the flattening process for a tree (or a subtree), we reset the prev variable to NULL. This ensures that the last node in the flattened list will correctly point to NULL instead of some node from a previous test case or a previous run.
Auxiliary Recursive Function: We’ve split the logic into two functions:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* prev = NULL;
void flatten_recursive(struct TreeNode* root) {
if (!root) return;
flatten_recursive(root->right);
flatten_recursive(root->left);
root->right = prev;
root->left = NULL;
prev = root;
}
void flatten(struct TreeNode* root) {
prev = NULL; // Reset the prev variable
flatten_recursive(root);
}