Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3]
]
这个题目要采用广度优先遍历,所以我们需要一个队列,为了记录节点的深度我用了一个map映射来记录节点的深度
当vec的长度小于节点的深度时,就需要插入一个新的向量,否则直接在向量上插入节点的val
最后我们再翻转vec,即为所求答案
/** * 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: void breadthFirstSearch(TreeNode* root, vector<vector<int>> &vec) { if (!root)return; queue<TreeNode*> que; map<TreeNode*, int> ma; que.push(root); ma[root] = 0; while (!que.empty()) { TreeNode* node = que.front(); if (node->left) { que.push(node->left); ma[node->left] = ma[node] + 1; } if (node->right) { que.push(node->right); ma[node->right] = ma[node] + 1; } if (vec.size() <= ma[node]) { vector<int> childvec; childvec.push_back(node->val); vec.push_back(childvec); } else { vec[ma[node]].push_back(node->val); } que.pop(); } } vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> vec; breadthFirstSearch(root, vec); reverse(vec.begin(), vec.end()); return vec; } };