2011-10-20 45 views
1

我能打印我的表達式樹的序。但我需要能夠用圓括號打印它。例如後序53+應該輸出(5 + 3)打印表達式樹

我目前有:

void printTree(struct TreeNode *tree) 
{ 
    if (tree != NULL) 
    { 
     if (isalpha(tree->info) || isdigit(tree->info)) 
     cout << "("; 
     printTree(tree->left); 
     cout<< tree->info; 
     printTree(tree->right); 
     if (isalpha(tree->info) || isdigit(tree->info)) 
     cout << ")"; 
    } 
} 

但是這給了我不正確的輸出。如果我輸入後綴表達式5分之62+它給我(6)/(2)+(5)

:(

+0

什麼是 「序」? –

+0

@Tomalak:http://en.wikipedia.org/wiki/Tree_traversal#Depth-first_Traversal –

+0

@SanderDeDycker:鉭 –

回答

2

您需要的葉節點和非葉節點之間進行區分。只有非葉節點被包含在邊界中。

bool isLeaf(struct TreeNode* tree) { 
    return tree->left == 0 && tree->right == 0; 
} 

void printTree(struct TreeNode* tree) { 
    if (tree != NULL) { // this test could be omitted if the printed tree is not empty 
     if (isLeaf(tree)) { 
      cout << tree->info; 
     } 
     else { 
      cout << "("; 
      printTree(tree->left); 
      cout << tree->info; 
      printTree(tree->right); 
      cout << ")";    
     } 
    } 
} 
1

嘗試反轉if條件決定括號是否應該打印:

void printTree(struct TreeNode *tree) 
{ 
    if (tree != NULL) 
    { 
     if (!(isalpha(tree->info) || isdigit(tree->info))) 
      cout << "("; 
     printTree(tree->left); 
     cout<< tree->info; 
     printTree(tree->right); 
     if (!(isalpha(tree->info) || isdigit(tree->info))) 
      cout << ")"; 
    } 
} 

或者甚至可能更好。

void printTree(struct TreeNode *tree) 
{ 
    if (tree != NULL) 
    { 
     if (isoperator(tree->info)) 
      cout << "("; 
     printTree(tree->left); 
     cout<< tree->info; 
     printTree(tree->right); 
     if (isoperator(tree->info)) 
      cout << ")"; 
    } 
} 

其中isoperator適當定義爲從操作數區分運營商