问题简述
给定一棵二叉树,返回该二叉树自底向上遍历的结点值(即从左到右,自底向上)
比如给定一颗二叉树 [3,9,20,null,null,15,7]
3/ \
9 20/ \
15 7
返回的结果为
[[15,7],[9,20],[3]
]
解决方案
解法1:广度优先遍历(BFS)
最简单的想法就是先广度优先遍历,按层存值,最后倒一下~
直接上代码
/*** 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;private:void _bfs(TreeNode* root){queue<TreeNode*> q;q.push(root);while (!q.empty()){int len = q.size();vector<int> vec;for (int i = 0; i < len; i++){TreeNode* tmp = q.front();q.pop();if (tmp->left)q.push(tmp->left);if (tmp->right)q.push(tmp->right);vec.push_back(tmp->val);}res.push_back(vec);}}public:vector<vector<int>> levelOrderBottom(TreeNode* root) {res.clear();if (!root)return res;_bfs(root);reverse(res.begin(), res.end());return res;}
};
解法2:深度优先遍历(DFS)
另一种做法是,一边深度遍历,一边按照层数记录数据
/*** 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;private:void _dfs(TreeNode* root, int layer){if (!root)return;if (layer >= res.size()){res.insert(res.begin(), vector<int>());}res[res.size() - layer - 1].push_back(root->val);_dfs(root->left, layer + 1);_dfs(root->right, layer + 1);}public:vector<vector<int>> levelOrderBottom(TreeNode* root) {res.clear();if (!root)return res;_dfs(root, 0);return res;}
};