码迷,mamicode.com
首页 > 编程语言 > 详细

Python3解leetcode Same TreeBinary Tree Level Order Traversal II

时间:2019-06-23 15:34:57      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:else   注意   rsa   erb   pre   python   12px   style   思路   

问题描述:

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

标签:else   注意   rsa   erb   pre   python   12px   style   思路   

原文地址:https://www.cnblogs.com/xiaohua92/p/11072788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!