Python3解leetcode Same TreeBinary Tree Level Order Traversal II

问题描述:

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

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

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

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

注意是每一层的所有数字放入同一个list内

思路:二叉树问题,考虑使用递归算法,计算出每一层的所有元素值

 

# 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]]: 
        if root == None: return []
        def order(rootx,level):
            if rootx == None:return
            if (level) == len(result):
                result.append([rootx.val])
            else:
                result[level].append(rootx.val)
            order(rootx.left,level+1)
            order(rootx.right,level+1)
        
        result = []
        order(root,0)
        return result[::-1]   

 

posted on 2019-06-23 14:37  狂奔的蜗牛163  阅读(184)  评论(0编辑  收藏  举报