给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
详见:https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> res; if(!root) { return res; } queue<TreeNode*> que; que.push(root); vector<int> out; int i=1; while(!que.empty()) { root=que.front(); que.pop(); --i; if(root->left) { que.push(root->left); } if(root->right) { que.push(root->right); } out.push_back(root->val); if(i==0) { res.insert(res.begin(),out); i=que.size(); out.clear(); } } return res; } };