Leetcode, Flatten Binary Tree to Linked List

Source: Internet
Author: User

According to the hint, the subject is equivalent to the pre order Traverse traversal, and in turn all nodes are saved to right child, and the left child is defined as an empty set. With recursive thinking, then if we separate the left and right subtree flatten into a list, we have:

1

/    \

2 5

\       \

3 6 <-Righttail

\

4 <-Lefttail

So use recursive solution one: note that since the right subtree is finally connected to the back of the Zuozi, save the head of the right subtree with temp.

1 defFlatten (self, root):2         """3 : Type Root:treenode4 : rtype:void do not return anything, modify root in-place instead.5         """       6         if  notRoot:7             return         8 Self.flatten (root.left)9 Self.flatten (root.right)Ten          Onetemp =Root.right A          -Root.right =Root.left -Root.left =None the          -          whileRoot.right: -Root =Root.right -          +Root.right = Temp

Leetcode, 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.