This article is in the study summary, welcome reprint but please specify Source: http://blog.csdn.net/pistolove/article/details/42744919
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
Ideas:
(1) Test instructions is a linked list (tree) that transforms a given two-fork tree into a "only right child node".
(2) by the know, if the right subtree is not empty, then the right subtree is certainly the Zuozi of the right child node, and the Zuozi finally becomes the right sub-tree of the whole tree. In this way, first determine whether Zuozi is empty, not empty to find the left child node of the root, and then look for the node whether there is a right child, if you have to continue to find the right child belonging to the leaf node, at this point, the right sub-tree of the node "point to" the right subtree of the current tree, and the current left Empty the left child of the whole tree. Finally, the root node "points" to the right child of the root node, continuing with the above operation until the entire tree is traversed to get the result.
(3) Hope this article is helpful to you.
The algorithm code is implemented as follows:
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; *
treenode (int x) {val = x;} *} */public void Flatten (TreeNode root) {while (root = null) {if (root.left! = null) {Tree Node pre = Root.left;while (pre.right! = null) Pre = Pre.right;pre.right = Root.right;root.right = Root.left;root.left = Nu ll;} root = Root.right;}}
Flatten Binary Tree to Linked List