标签:tor tom public 层序遍历 rbegin ott code 思路 ++
Easy!
题目描述:
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / 9 20 / 15 7
返回其自底向上的层次遍历为:
[ [15,7], [9,20], [3] ]
解题思路:
从底部层序遍历其实还是从顶部开始遍历,只不过最后存储的方式有所改变,参见http://www.cnblogs.com/grandyang/p/4051321.html,代码如下:
C++解法一:
1 // Iterative 2 class Solution { 3 public: 4 vector<vector<int> > levelOrderBottom(TreeNode *root) { 5 vector<vector<int> > res; 6 if (root == NULL) return res; 7 8 queue<TreeNode*> q; 9 q.push(root); 10 while (!q.empty()) { 11 vector<int> oneLevel; 12 int size = q.size(); 13 for (int i = 0; i < size; ++i) { 14 TreeNode *node = q.front(); 15 q.pop(); 16 oneLevel.push_back(node->val); 17 if (node->left) q.push(node->left); 18 if (node->right) q.push(node->right); 19 } 20 res.insert(res.begin(), oneLevel); 21 } 22 return res; 23 } 24 };
下面我们来看递归的解法,核心就在于我们需要一个二维数组,和一个变量level,当level递归到上一层的个数,我们新建一个空层,继续往里面加数字。
C++解法二:
1 // Recurive 2 class Solution { 3 public: 4 vector<vector<int>> levelOrderBottom(TreeNode* root) { 5 vector<vector<int> > res; 6 levelorder(root, 0, res); 7 return vector<vector<int> > (res.rbegin(), res.rend()); 8 } 9 void levelorder(TreeNode *root, int level, vector<vector<int> > &res) { 10 if (!root) return; 11 if (res.size() == level) res.push_back({}); 12 res[level].push_back(root->val); 13 if (root->left) levelorder(root->left, level + 1, res); 14 if (root->right) levelorder(root->right, level + 1, res); 15 } 16 };
标签:tor tom public 层序遍历 rbegin ott code 思路 ++
原文地址:https://www.cnblogs.com/ariel-dreamland/p/9162461.html