![fbc1d2c0adce143d1a7d10613dc6d257.png](https://i-blog.csdnimg.cn/blog_migrate/c202fb0f9d38c7aeee23e39d20e7556c.jpeg)
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3 / 9 20 / 15 7
返回其自底向上的层次遍历为:
[ [15,7], [9,20], [3]]
![5c30bc231bb1d3887f8648e6f0fe6b54.png](https://i-blog.csdnimg.cn/blog_migrate/85cc472076791b6fb74e7c27ab623dbc.jpeg)
解:
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root: return [] stack=[root] res=[] while stack: temp=[] res_each=[] for i in stack: res_each.append(i.val) if i.left: temp.append(i.left) if i.right: temp.append(i.right) stack=temp res.insert(0,res_each) return res