1. 程式人生 > >CS106B Section Solutions #8

CS106B Section Solutions #8

這章重點是樹的操作,有樹的遍歷,判斷樹相等,刪除葉子節點,平衡樹,幾乎都要用到遞迴

Problem 1: Extending Editor Buffer

解決將位置移到一段話中單詞開頭的問題

陣列的操作簡單,單鏈表操作學習下套路,用curr 和prev 兩個指標從head一步步遍歷的方法

//array implementation
void Buffer::moveToWordBegin()
{
    //如果前面是空格,則跳過所有空格,至不是空格的位置
    whlie(currse -1 >= 0 && isspace(text[cursor-1]))
    moveCursorBackward();
    //如果不是空格,則跳至是空格的位置
    whlie(currse -1 >= 0 && !isspace(text[cursor-1]))
    moveCursorBackward();

}

//stack implementation
void Buffer::moveToWordBegin()
{
    whlie(!before -> IsEmpty()  && isspace(before -> peek()))  //看樣子得給出private的內容才寫的出呀
    moveCursorBackward();
    
    whlie(!before -> IsEmpty()  && !isspace(before -> peek()))
    moveCursorBackward();

}

//singly linked-list implementation
//因為是單鏈表,所以需要從頭開始,尋找單詞開頭
void Buffer::moveToWordBegin()
{
    cellT* wordStart, curr, prev;
    if(cursor != head)
    {
        curr = head->link;
        prev = head;
        whlie(curr != cursor) //找出最近的單詞開頭
        {
            if(isspace(prev->value) && !isspace(curr->value))//判斷是否是單詞開頭
                wordStart = curr;
            prev = curr;
            curr = curr->link;
        }
        cursor = wordStart;
    }
}

Problem 2: Tree Trivia

a)  4     B, H, W     C

b) 前序 : G C B M H R W

    中序:  B C G H M R W     後序:  B C H W R M G

c) D 是 C 的右孩子

d) G

e) 是前序: G C B M H R W

Problem 3: Tree Equal

比較兩個樹是否一樣,採用遞迴寫法

bool TreeEqual(noteT *t1, noteT *t2)
{
    //遞迴最小情況:都是空
    if((t1 == NULL) && (t2 == NULL))
    return true;
    //一方為空,另一方不是,返回0
    if((t1 == NULL) || (t2 == NULL))
    return false;
    //真是精簡
    return ( (t1->key == t2->key) &&
             TreeEqual(t1->left, t2->left) &&
             TreeEqual(t1->right, t2->right) )
    )
}

Problem 4: TrimLeaves

a) 刪除葉子節點,簡單遞迴實現

void TrimLeaves(nodeT* tree)
{
    if(tree == NULL)
    return;
    if(tree->left == NULL && tree->right == NULL)
    {
        delete tree;  //不要忘記這一步
        tree = NULL;
    }
    Trimleaves(tree->left);
    TrimLeaves(tree->right);
}

b) 很明顯採用引用傳遞

Problem 5: Balanced Trees

計算樹的長度

int TreeHeight(nodet* tree)
{
    if(tree == NULL)
    return 0;
    else
    return 1+ max(TreeHeight(tree->left), TreeHeight(TreeHeight(tree->right)));
}

判斷樹否是平衡樹

bool IsBalanced(nodeT* t)
{
    if(t == NULL)
    return true;
    else return ((abs(TreeHeight(t->left), TreeHeight(t->right)) <= 1) &&
                 IsBalanced(t->left) &&
                 IsBalanced(t->right));
}

可以慢慢弄清解決樹問題的套路了, 一般是判斷是否是NULL,在進行左右子樹的遞迴。