Flatten Binary Tree to Linked List
Note that the problem requires in-place operation.The flatten procedure is like: cut the left child and set to right, the right child is then linked to somewhere behind the left child. Where should it be then? Actually the right child should be linked to the most-right node of the left node. So the algorithm is as follows:(1) store the right child (we call R)(2) find the right-most node of left child(3) set R as the right-most node's right child.(4) set left child as the right child(5) set the left child NULL(6) set current node to current node's right child.(7) iterate these steps until all node are flattened.
void flatten(TreeNode* root) {
TreeNode p=root, temp;
while(p){
temp=p->left;
if(temp){
while(temp->right)
temp=temp->right;
temp->right=p->right;
p->right=p->left;
p->left=nullptr;
}
p=p->right;
}
}
Last updated
Was this helpful?