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,在进行左右子树的递归。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值