/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector > levelOrderBottom(TreeNode *root) { int depth = Depth(root); vector > bottom; if (root == NULL) return bottom; deque dq; dq.push_back(root); /* 这里是利用队列来进行存储每一行的节点,进队列出队列,主要思路就是利用当前的遍历到当前节点,就讲它的左右子节点 进入队列,然后再将这一个队列的当前行的元素进入vector中然后在进入二维数组中 */ while (!dq.empty()){ int low = 0; int high = dq.size();//计算当前队列中元素的个数,这个就是每一行的元素个数 vector tmp; while (low++ < high){ TreeNode *cur = dq.front(); dq.pop_front(); tmp.push_back(cur->val); if (cur->left) dq.push_back(cur->left); if (cur->right) dq.push_back(cur->right); } bottom.push_back(tmp); } reverse(bottom.begin(), bottom.end());//翻转函数,实现翻转 return bottom; } //计算树的深度函数 int Depth(TreeNode *root){ if (root == NULL) return 0; int left = left + Depth(root->left); int right = right + Depth(root->right); return left>right?left:right; }};