Lintcode-easy-flatten Binary Tree to Linked List

Source: Internet
Author: User

Flatten a binary tree to a fake "linked list" in pre-order traversal.

Here we use the right pointer in TreeNode as the nextpointer in ListNode.

Example
              1                    1          2    / \             2   5    =>    3  / \   \           3   4   6          4                                           5                                               6
Note

Don ' t forget to mark the left child of each node to null. Or you'll get time limit exceeded or Memory Limit exceeded.

Challenge

Do it in-place without any extra memory.

Recursively, note if the left dial hand tree is null directly flatten the right subtree and then returns, otherwise times out

/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/**     * @paramroot:a TreeNode, the root of the binary tree *@return: Nothing*/     Public voidFlatten (TreeNode root) {//Write your code here        if(Root = =NULL)            return; if(Root.left = =NULL&& Root.right = =NULL)            return; if(Root.left! =NULL) {flatten (root.left); }                if(Root.right! =NULL) {flatten (root.right); } TreeNode Temp=Root.right; if(Root.left! =NULL) {Root.right=Root.left; Root.left=NULL; TreeNode P=Root;  while(P.right! =NULL) P=P.right; P.right=temp; }                                return; }}

Lintcode-easy-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.