题目
给定一个二叉树,返回其节点值自底向上的层序遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
返回其自底向上的层序遍历为:
[ [15,7], [9,20], [3] ]
解题
在leetcode-102:二叉树的层序遍历的基础上,最后返回的时候 反 一下就行了
python写法
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: if not root: return [] res = [] queue = [root] while queue: l = len(queue) tmp = [] for _ in range(l): cur = queue.pop(0) tmp.append(cur.val) left,right = cur.left,cur.right if left: queue.append(left) if right: queue.append(right) res.append(tmp) return res[::-1]
c++写法
class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { if(!root) return {}; vector<vector<int>> res; queue<TreeNode*> queue; queue.push(root); while(!queue.empty()){ vector<int> tmp; int l=queue.size(); while(l--){ TreeNode* cur=queue.front(); queue.pop(); tmp.push_back(cur->val); TreeNode* left=cur->left; TreeNode* right=cur->right; if(left){ queue.push(left); } if(right){ queue.push(right); } } res.push_back(tmp); } reverse(res.begin(),res.end()); return res; } };