LeetCode Binary Tree Level Order Traversal II
class Solution { private: vector<vector<int> > nodes; public: vector<vector<int> > levelOrderBottom(TreeNode *root) { nodes.clear(); dfs(root, 0); reverse(nodes.begin(), nodes.end()); return nodes; } void dfs(TreeNode* root, int level) { if (root == NULL) return; if (level >= nodes.size()) { nodes.push_back(vector<int>()); } nodes[level].push_back(root->val); dfs(root->left, level + 1); dfs(root->right, level + 1); } };
复杂度应该不会有不同, 应该有更好的方法,不用做reverse
第二轮:
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] ]
几乎一样的代码,可以用链表避免做reverse
第三轮:
先求出树德最大高度就可以避免做reverse。
/** * 7:13 * 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 { private: vector<vector<int> > res; public: vector<vector<int>> levelOrderBottom(TreeNode* root) { int h = height(root); res = vector<vector<int> >(h); if (h == 0) { return res; } dfs(root, h - 1); return res; } int height(TreeNode* root) { if (root == NULL) { return 0; } int dl = height(root->left); int dr = height(root->right); return 1 + max(dl, dr); } void dfs(TreeNode* root, int idx) { if (root == NULL) { return; } dfs(root->left, idx - 1); dfs(root->right, idx - 1); res[idx].push_back(root->val); } };