Python3解leetcode Same TreeBinary Tree Level Order Traversal II

Posted xiaohua92

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]   

 

以上是关于Python3解leetcode Same TreeBinary Tree Level Order Traversal II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Same Tree

C解1.Two Sum——LeetCode刷题

Python3解leetcode Isomorphic Strings

Python3解leetcode Linked List Cycle

Python3解leetcode Factorial Trailing Zeroes

Python3解leetcode Subtree of Another Tree