Leetcode 107 binary tree traversal,

107. The binary tree traversal

Given a binary tree, the node returns its bottom-up value hierarchy traversal. (Ie, by physical layer to the layer from the leaf nodes of the root node, layer by layer traversal from left to right)

For example:
given binary tree [3,9,20, null, null, 15,7 ],

3
/ \
920
/ \
157
returns to its level from the bottom-up traversal of:

[
[15,7],
[9,20],
[3]
]

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/binary-tree-level-order-traversal-ii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

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

class Solution:
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
l = []
if not root:
return l
tmp = [root]
while tmp:
tmp_l = []
tmp_bianli = []
for item in tmp:
tmp_l.append(item.val)
if item.left:
tmp_bianli.append(item.left)
if item.right:
tmp_bianli.append(item.right)
l.append(tmp_l)
tmp = tmp_bianli
return l[::-1]

Guess you like

Origin www.cnblogs.com/xqy-yz/p/11411160.html