Flatten Binary Tree to Linked List, flattenlinked

Source: Internet
Author: User

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;}}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.