値ノードの親を返す関数を作成しようとしています。createAB関数は機能しますが、バイナリツリー要素を繰り返し処理することはわかりません。再帰呼び出しを行う方法?。私を助けてください。バイナリツリー、ノードの親を返す
ifstream f("store.txt");//store.txt:10 7 8 0 0 0 13 9 0 11 0 0 12 0 0
struct elem {
int inf;
elem* st;
elem* dr;
};
//this function create the binary tree
void createAB(elem*& p) {
int n;
f >> n;
if (n!=0) {
p = new elem;
p->inf = n;
createAB(p->st);
createAB(p->dr);
}
else
p = NULL;
}
`
elem* parent(elem* rad, int n) {//my function,doesn't work
if (rad == NULL)
return NULL;
else
if (rad->st->inf == n || rad->dr->inf == n)
return rad;//return the element
else {
return parent(rad->st, n);//here is a problem
return parent(rad->dr, n);
}
}
10
7 13
8 9 12
11
node 12 => parent 13
node 8 => parent 7
は端末ノードでは機能しません – paulc
@paulc私は完全な機能を追加しました。少なくともそれは私のために働く。 –
ありがとう!!!再帰なしでこの関数を書くにはどうすればいいですか? – paulc