题目来源:
https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
题意分析:
从底向上宽度遍历二叉树。
题目思路:
自顶向下遍历二叉树后将答案翻转。
代码(python):
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ans = [] def bfs(root,level): if root != None: if len(ans) < level + 1: ans.append([]) ans[level].append(root.val) bfs(root.left,level + 1) bfs(root.right,level + 1) bfs(root,0) ans.reverse() return ans
时间: 2024-11-08 16:05:35