给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
返回其自底向上的层次遍历为:
[ [15,7], [9,20], [3] ]
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 #include<algorithm> 11 class Solution { 12 public: 13 vector<vector<int>> levelOrderBottom(TreeNode* root) { 14 queue<TreeNode*> q; 15 q.push(root); 16 vector<vector<int>> ans; 17 if(root == NULL) return ans; 18 while(!q.empty()){ 19 queue<TreeNode*> qt; 20 vector<int> t; 21 while(!q.empty()){ 22 TreeNode* temp = q.front(); 23 q.pop(); 24 t.push_back(temp->val); 25 if(temp->left) qt.push(temp->left); 26 if(temp->right) qt.push(temp->right); 27 } 28 ans.push_back(t); 29 q = qt; 30 } 31 reverse(ans.begin(), ans.end()); 32 return ans; 33 } 34 };