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
The pre-sequence traversal, each layer records the current node's left and right child nodes, with tail record the modified list end, and return to the previous layer. Note that the left and right of the current node is empty before modifying the structure.
1 Public classFlattenbinarytreetolinkedlist {2 Public voidFlatten (TreeNode root) {3 Dfs (root);4 }5 6 PublicTreeNode dfs (TreeNode root) {7 if(Root = =NULL) {8 return NULL;9 }TenTreeNode left =Root.left; OneTreeNode right =Root.right; A //leave the left and right children of the current node empty -Root.left =NULL; -Root.right =NULL; theTreeNode tail =Root; - //connecting the left subtree - if(Left! =NULL) { -Tail.right =Left ; +Tail =Dfs (left); - } + //Connect right subtree A if(Right! =NULL) { atTail.right =Right ; -Tail =Dfs (right); - } - returntail; - } -}
Flatten Binary Tree to Linked List