题目:
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,#,#,15,7}
,
3 / 9 20 / 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
提示:
此题要求从下往上,从左往右逐行输出二叉树的节点数值,这里提供两种解法,分别是递归和迭代。
代码:
递归:
/** * 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) { levelOrder(root, 0); reverse(res.begin(), res.end()); return res; } private: void levelOrder(TreeNode* root, int currLevel) { if (root == NULL) return; if (res.empty() || currLevel > (res.size() - 1)) res.push_back(vector<int>()); res[currLevel].push_back(root->val); levelOrder(root->left, currLevel + 1); levelOrder(root->right, currLevel + 1); } vector<vector<int>> res; };
迭代:
/** * 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>> res; if (!root) return res; stack<vector<int>> s; vector<int> v; TreeNode *node; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; ++i) { node = q.front(); q.pop(); v.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } s.emplace(move(v)); v.clear(); } while(!s.empty()) { res.emplace_back(move(s.top())); s.pop(); } return res; } };