"114-flatten binary tree to Linked list (binary trees to single linked list)"
"leetcode-Interview algorithm classic-java Implementation" "All Topics folder Index"
Original Question
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
Main Topic
Given a tree of two forks. Turn it into a single-linked list, using the in-place algorithm.
Thinking of solving problems
From root node (root), find the right-most node (x) of Zuozi (L). Connect the right subtree of root (r) to the right sub-tree of x (the right subtree of x is empty). The left subtree of root is generally adjusted to the right subtree, and the left subtree of root is empty.
Code Implementation
Tree Node class
publicclass TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
Algorithm implementation class
Public classSolution { Public void Flatten(TreeNode Root) {TreeNode head =NewTreeNode (-1); Head.right = root; TreeNode node = head; while(Node.right! =NULL) {node = node.right;if(Node.left! =NULL) {TreeNode end = Node.left; while(End.right! =NULL) {end = End.right; } TreeNode tmp = Node.right; Node.right = Node.left; Node.left =NULL; End.right = tmp; }} head.right =NULL;//Remove references for easy garbage collection}}
Assessment Results
Click on the picture, the mouse does not release, drag a position, release after the new form to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47438085"
"Leetcode-Interview algorithm classic-java implementation" "114-flatten binary Tree to Linked list (binary trees to single linked list)"