給定一個二叉樹,返回其節點值自底向上的層次遍歷。 (即按從葉子節點所在層到根節點所在的層,逐層從左向右遍歷)node
例如:
給定二叉樹 [3,9,20,null,null,15,7],ide3 / \ 9 20 / \ 15 7返回其自底向上的層次遍歷爲:code
[ [15,7], [9,20], [3] ]
解題思路:首先temp臨時記錄層次遍歷每一層的結點值,當遍歷到下一層的結點時就將temp記錄到result中.it
代碼實現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<pair<TreeNode*,int> > Queue; vector<int> temp; //臨時記錄每一層的節點值 Queue.push(make_pair(root,0)); while(!Queue.empty()) { TreeNode* node = Queue.front().first; int step = Queue.front().second; Queue.pop(); if(result.size() == step - 1) { result.push_back(temp); temp.clear(); temp.push_back(node->val); } else { temp.push_back(node->val); } if(node->left) Queue.push(make_pair(node->left, step + 1)); if(node->right) Queue.push(make_pair(node->right, step + 1)); } result.push_back(temp); reverse(result.begin(),result.end()); return result; } };