您的位置:首页 > 其它

[LeetCode]Binary Tree Level Order Traversal II

2015-07-22 13:42 525 查看
解题思路:
反正都要遍历。深度搜索 或者 宽度搜索都可以,就看你怎么把需要返回的vector构建起来;

方法一:
宽度搜索:
1,边界条件:root == NULL
2,前条件,2个queue,一个存放 node,一个存放对应node的深度; depth记录当前深度;1个stack,把每一层的vector压栈,最后倒序取出,插入vector<vector>>
3,不变式:把node的左右子树加入queue1,相应depth加入queue2;
4,结束条件:queue1为空,然后把stack的元素依次取出,push_back到vector<vector>中

//编译错误,除了两次手残打错-> 和vector<int>,改过来之后直接AC
/**
* 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> > ret;
if (root == NULL){
return ret;
}
int depth = 0;
queue<TreeNode* > qNode;
queue<int>  qDepth;
qNode.push(root);
qDepth.push(depth);

stack<vector<int> > arrays;

while(!qNode.empty()){
TreeNode* node = qNode.front();
qNode.pop();

depth = qDepth.front();
qDepth.pop();

if (node->left != NULL){
qNode.push(node->left);
qDepth.push(depth + 1);
}

if (node->right != NULL){
qNode.push(node->right);
qDepth.push(depth + 1);
}

if (arrays.size() <= depth){
vector<int> v;
v.push_back(node->val);
arrays.push(v);
}else{
arrays.top().push_back(node->val);
}
}

while(!arrays.empty()){
ret.push_back(arrays.top());
arrays.pop();
}

return ret;
}
};


方法二:
深度搜索(反面教材):
1,边界条件:node的左右子树均为NULL,把node->val 加入到vector[0].push_back(node->val);
2,前条件:左右子树的深度 ldepth , rdepth 设置为0
3,不变式:递归调用 dfs 获取子树的depth;本层的深度depth为max{ldepth, rdepth} + 1,根据深度加入vector
4,结束条件:遍历整棵树

// 但是,这个问题如果用深度搜索,需要考虑的边界问题比较多;
// 以下是错误代码,错误原因有如下总结:
1,遍历至leaf node时,leaf的深度不一定是0,不能马上插入vector
2,发现上述问题后,我改变方法,不在leaf node插入,在中间的node插入。但是,仔细思考,只有在
深度搜索遍历整个树之后,才能确定lead node的深度(为什么要确定深度再insert,因为深度搜索是从leaf node开始insert的)。所以dfs在这个问题上需要走两个遍历。
第一遍是发现 height;
第二遍才可以一边遍历一边插入vector
下面的代码,存在上述第2个问题,想到这里,我还是改用宽度搜索咯。下面代码WA,可忽略

/**
* 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> > ret;
if (root == NULL){
return ret;
}

int depth = bfs(root, ret);
insertToVector(ret, depth, root->val);

return ret;
}

int bfs(TreeNode* root, vector<vector<int> > &vec){
if (root->left == NULL && root->right == NULL){
return 0;
}
int ldepth = 0;
int rdepth = 0;
if (root->left != NULL){
ldepth = bfs(root->left, vec);
}
if (root->right != NULL){
rdepth = bfs(root->right, vec);
}

int depth = max(ldepth, rdepth) + 1;

if (root->left != NULL){
insertToVector(vec, depth-1, root->left->val);
}
if (root->right != NULL){
insertToVector(vec, depth-1, root->right->val);
}

return depth;
}

void insertToVector(vector<vector<int> > &vec, int depth, int val){
if (vec.size() <= depth){
vector<int> v;
v.push_back(val);
vec.push_back(v);
}else{
vec[depth].push_back(val);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: