Leetcode algorithm: Find largest Value in each Tree Row

Source: Internet
Author: User

" "
You need to find the largest value in each row of a binary tree.

Example:
Input:

1
/ \
3 2
/ \ \
5 3 9

Output: [1, 3, 9]


" "

# Definition for a binary tree node.
# class TreeNode (object):
# def __init__ (self, x):
# self.val = x
# self.left = None
# self.right = None


This title describes:
give us a binary tree root node that returns an array of the maximum values for each layer


thought:
breadth-first traversal, placing the maximum value of each layer into the result list

python implementations:
1 classsolution (object):2     deflargestvalues (self, root):3         """4 : Type Root:treenode5 : Rtype:list[int]6         """7         if  notRoot:8             return []9levels =[[Root]]TenValues =[[Root.val]] One          forLevelinchlevels: ANext_level = [] -Value = [] -              forNodeinchLevel : the                 ifNode.left is  notNone: - next_level.append (node.left) - value.append (node.left.val) -                 ifNode.right is  notNone: + next_level.append (node.right) - value.append (node.right.val) +             ifNext_level: A levels.append (next_level) at values.append (value) -res = [] -          forVinchvalues: - res.append (Max (v)) -         returnRes


Streamline the code:
1 classsolution (object):2     deflargestvalues (self, root):3         """4 : Type Root:treenode5 : Rtype:list[int]6         """7Values = []8Level =[Root]9          whileAny (level):TenValues.append (Max ([I.val forIinchLevel ]) ) Onelevel = [Child forNodeinchLevel forChildinch[Node.left, Node.right]ifChild is  notNone] A         returnValues



Leetcode algorithm: Find largest Value in each Tree Row

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.