Flatten Binary Tree to Linked List

Source: Internet
Author: User

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

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.