2014-01-25 82 views
1

我正在創建自己的shell。在「按順序遍歷樹」中查找特定節點

我已經爲用戶輸入創建了詞法分析器和解析器(它創建了一個二叉樹)。 所以對於這樣的命令:cat main.c | ls | wc

我得到這個樹:

  "|" 
     /\ 
     / \ 
     / \ 
"cat main.c" "|" 
       /\ 
      / \ 
      "ls" "wc" 

所以我的樹遍歷功能(按順序)是這樣的:

inorder(root) 
{ 
    inorder(root->left); 
    //exec cmd and do redirection 

    inorder(root->right); 
} 

我的問題是,當我在節點「LS」或「 wc「,我不知道如何 檢查命令之前和之後是否有管道

有什麼想法?

+0

解析樹不是B樹。 – EJP

回答

1

在你的分析樹中,管道是節點,命令是樹葉。管道必須有左右分支。當你從一個管道離開時,你現在所處的管道就是你將要進入的命令的輸出管道。當你向右走時,你所在的管道是目標命令的管道。

所以通過輸入和輸出管道作爲參數。如果沒有該命令的重定向或|節點之一,則它們指向NULL

inorder(root, in, out) 
{ 
    if (root is cmd) { 
     execute(root, in, out); 
    } else { 
     // root is pipe 
     inorder(root->left, in, root); 
     redirect(in, out); 
     inorder(root->right, root, out); 
    } 
} 

inorder(root, NULL, NULL)開始在樹的根部。