題目:node
給定一個二叉樹,返回其節點值自底向上的層次遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)spa
例如:code
思路:採用寬度優先搜索。blog
時間複雜度:O(n)。n爲節點的數量,遍歷全部節點。it
空間複雜度:O(n)。建立一個vector容器存儲全部節點值。io
/** * 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> > result; if (root == NULL) return result; queue<TreeNode*> q; q.push(root); while(!q.empty()) { int len = q.size(); vector<int> temp; for (int i = 0; i < len; ++i) { TreeNode* node = q.front(); q.pop(); temp.push_back(node->val); if(node->left != NULL) q.push(node->left); if(node->right != NULL) q.push(node->right); } result.insert(result.begin(), temp); } return result; } };