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]
]
依旧是层序遍历而已,更另一篇博客一样,bfs或者dfs之后reverse一下就可以了,这里给出bfs版本,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:
struct Node{
TreeNode * treeNode;
int level;
Node(){}
Node(TreeNode * nd, int lv)
:treeNode(nd), level(lv){}
};
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ret;
if(!root)
return ret;
queue<Node> nodeQueue;
nodeQueue.push(Node(root, ));
int dep = -;
while(!nodeQueue.empty()){
Node node = nodeQueue.front();
if(node.treeNode->left)
nodeQueue.push(Node(node.treeNode->left, node.level + ));
if(node.treeNode->right)
nodeQueue.push(Node(node.treeNode->right, node.level + ));
if(dep == node.level)
ret[dep].push_back(node.treeNode->val);
else{
vector<int> tmp;
dep++;
ret.push_back(tmp);
ret[dep].push_back(node.treeNode->val);
}
nodeQueue.pop(); //不要忘了
}
reverse(ret.begin(), ret.end());
return ret;
}
};
上面写的可能结果是对的,但是好像不是题目本来的意思,下面用dfs重新写一遍
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
dfs(ret, root, 0);
Collections.reverse(ret);
return ret;
} public void dfs(List<List<Integer>> ret, TreeNode root, int dep){
if(root == null)
return;
if(ret.size() <= dep){
List<Integer> tmp = new ArrayList<Integer>();
ret.add(tmp);
}
ret.get(dep).add(root.val);
if(root.left != null) dfs(ret, root.left, dep+1);
if(root.right != null) dfs(ret, root.right, dep+1);
}
}