问题描述
问题链接是 https://practice.geeksforgeeks.org/problems/nodes-at-given-distance-in-binary-tree/1
给定一棵二叉树、二叉树中的一个目标节点和一个整数值k,找出与给定目标节点距离为k的所有节点。没有可用的父指针。
我的代码是
class Solution
{
private:
public:
void print(Node*root,int k,vector<int> &v){
if(root==NULL||k<0){
return;
}
if(k==0){
v.push_back(root->data);
return;
}
print(root->left,k-1,v);
print(root->right,v);
}
int check(Node* root,int target,vector<int> &v){
if(root==NULL){
return -1;
}
if(root->data == target){
print(root,k,v);
return 0;
}
int dl = check(root->left,target,v);
if(dl!=-1){
if(k==dl+1){
v.push_back(root->data);
}
else{
print(root->right,k-dl-2,v);
}
return dl+1;
}
int dr = check(root->right,v);
if(dr!=-1){
if(k==dr+1){
v.push_back(root->data);
}
else{
print(root->left,v);
}
return dr+1;
}
return -1;
}
vector <int> KdistanceNodes(Node* root,int k)
{
// return the sorted vector of all nodes at k dist
vector<int> v;
check(root,v);
sort(v.begin(),v.end());
return v;
}
};
我的代码同时传递了这个问题的示例和一些随机的自定义输入案例,但是当我提交时,它显示了一个测试案例,我的代码没有显示输出,我无法理解为什么会发生这种情况。 请告诉我代码中缺少什么。您也可以通过将此代码复制粘贴到 geeks for geeks 网站中上面给出的问题链接来尝试相同的操作。I have given the image link of testcase which is not passed by my code here
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)