Leetcode tree related problems (update continuously)

Source: Internet
Author: User

Leetcode binary tree level order traversal

This is a binary tree hierarchy traversal. The simplest and most intuitive method for hierarchy traversal is BFs. Therefore, we only need to maintain a queue. The elements in the queue need to record the content of the node and the layer where the node is located, and then retrieve the nodes from the queue for expansion.

# Definition for a  binary tree node# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    # @param root, a tree node    # @return a list of lists of integers    def levelOrder(self, root):        if(root == None):            return []                queue = []        queue.append((0, root))                ans = []        cur = 0        cur_nodes = []        while len(queue) != 0:            level, fa = queue.pop(0)            if(level == cur):                cur_nodes.append(fa.val)            else:                ans.append(cur_nodes)                cur_nodes = []                cur_nodes.append(fa.val)                cur = level            if fa.left != None:                queue.append((level+1, fa.left))            if fa.right != None:                queue.append((level+1, fa.right))        ans.append(cur_nodes)        return ans                


Leetcode tree related problems (update continuously)

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.