找到树的中序遍历并通过否定每个交替数字来打印它们
find the inorder traversal of the tree and print them all by negating every alternate number
例如:
1
/ \
/ \
2 3
/ \ / \
4 5 6 7
中序遍历输出:4 2 5 1 6 3 7
预期输出:4 -2 5 -1 6 -3 7
顺序代码是
Node * func(struct Node * root){
if(root!=NULL)
{
func(root->lChild);
cout<<root->nodeValue<<" ";
func(root->rChild);
}
return NULL;
}
您可能需要做的就是添加一个额外的参数来跟踪备用符号,如下所示:
Node * func(struct Node * root, int& signV ){
if(root!=NULL)
{
func(root->lChild, signV);
cout<<root->nodeValue * signV <<" "; signV *= -1 ; // Change sign here
func(root->rChild, signV);
}
return NULL;
}
例如:
1
/ \
/ \
2 3
/ \ / \
4 5 6 7
中序遍历输出:4 2 5 1 6 3 7
预期输出:4 -2 5 -1 6 -3 7
顺序代码是
Node * func(struct Node * root){
if(root!=NULL)
{
func(root->lChild);
cout<<root->nodeValue<<" ";
func(root->rChild);
}
return NULL;
}
您可能需要做的就是添加一个额外的参数来跟踪备用符号,如下所示:
Node * func(struct Node * root, int& signV ){
if(root!=NULL)
{
func(root->lChild, signV);
cout<<root->nodeValue * signV <<" "; signV *= -1 ; // Change sign here
func(root->rChild, signV);
}
return NULL;
}