DFS遍历树时无法判断子节点是否为空

zoroyihan 2019-08-13 01:57:34
#include <vector>
#include <string>
#include <iostream>

using namespace std;


class Solution {

private:
vector<string> vs;
int N;

struct point {
char data;
struct point* lchild, *rchild;
int num_l = 0, num_r = 0;
point(char c, int l, int r) :data(c), num_l(l), num_r(r), lchild(NULL), rchild(NULL) {
}
};
public:

//为什么DFS遍历树时无法判断 子节点是否为空, 子节点即使为空也会进入递归导致内存泄漏报错
void dfs(point* root, string s) {

if (NULL == root)
return;
s += root->data;
if (NULL == root->lchild &&NULL == root->rchild )
{
vs.push_back(s);
}
else {
dfs(root->lchild, s);
dfs(root->rchild, s);
}
}

point* CreatBiTree(char c, int l, int r)
{
if (r == N + 1)
return nullptr;
point *p;

p = (point*)malloc(sizeof(point));
p->data = c;
p->num_l = l;
p->num_r = r;

if (l == N) //前面的
{
p->rchild = CreatBiTree(')', l, r + 1);

}
else {

if (l == r)
p->lchild = CreatBiTree('(', l + 1, r);
else if (l >r)
{
p->lchild = CreatBiTree('(', l + 1, r);
p->rchild = CreatBiTree(')', l, r + 1);
}
}

return p;


}

vector<string> generateParenthesis(int n) {
N = n;
point* root = NULL;
root = CreatBiTree('(', 1, 0);

string s;
dfs(root, s);
return vs;
}
};

int main() {
Solution s;

vector<string> vs = s.generateParenthesis(2);
for (vector<string>::iterator it = vs.begin(); it != vs.end(); it++)
cout << *it << endl;


return 0;
}
...全文
87 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
真相重于对错 2019-08-13
  • 打赏
  • 举报
回复
c++不要用malloc free而要用new delete
zoroyihan 2019-08-13
  • 打赏
  • 举报
回复
在做leetcode 22.括号生成时 想利用先建树后深度遍历的方法输出所有结果 ,但是DFS这里这样写总是报错,明明算法本身没问题。

64,282

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧