Sword refers to the offer from top to bottom print binary tree (Python) __python

Source: Internet
Author: User
The topic description prints out each node of the two-fork tree from the top down, and the same layer node prints from left to right. Train of thought: Use two list, one to install node, one to load node value. For this list of loaded nodes, we pop up the front node each time and add the left and right nodes to the back in turn. In any case, this set of node list can guarantee that the node from top to bottom, the same layer of nodes from left to right to add, pop-up. The code is as follows:
Class TreeNode ():
    def __init__ (self,x):
        self.val = x
        self.left = none
        Self.right = None
def function (Root):
    a = [] result
    = []
    if not root: return result
    a.append (root) while
    A:
        Current_root = A.pop (0)
        result.append (current_root.val)
        if current_root.left:
            a.append (Current_ Root.left)
        if current_root.right:
            a.append (Current_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.