找到树的无序遍历,并通过否定每个备用数字来打印它们

find the inorder traversal of the tree and print them all by negating every alternate number

本文关键字:备用 数字 打印 无序 遍历      更新时间:2023-10-16

例如:

         1
      /      
    /         
  2             3
 /           / 
 4   5       6   7

顺序遍历输出:4 2 5 1 6 3 7

预期产量: 4 -2 5 -1 6 -3 7

Inorder 的代码是

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;
}

See Here