Flatten Binary Tree to Linked List, flattenlinked
This article is in the study of the summary, welcome to reprint but please note the 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 shoshould look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
Ideas:
(1) The question is to convert a given binary tree into a linked list (tree) with "only right child nodes ).
(2) We can see that if the right subtree is not empty, the right subtree must end with the right subtree with the right child node at the top of the Left subtree, the left subtree becomes the right subtree of the entire tree. In this way, first determine whether the left subtree is empty. If it is not empty, find the left child node of the root, and then find whether the node has the right child, until the right child of the leaf node is found, the right subtree of the node "points to" the right subtree of the current tree, and changes the current left subtree to the right child of the root, leave the left child of the entire tree empty. Finally, the root node points to the right child of the root node and continues the above operation until the whole tree is traversed.
(3) I hope this article will help 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) {TreeNode pre = root.left;while (pre.right != null)pre = pre.right;pre.right = root.right;root.right = root.left;root.left = null;}root = root.right;}}