DFS遍历树时无法判断子节点是否为空
#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;
}