本文共 612 字,大约阅读时间需要 2 分钟。
<BtNode* Parent(BtNode* ptr,BtNode* child){if(ptr==nullptr||ptr->leftchild==child||ptr->rightchild==child){return ptr;}else{BtNode* p=Parent(ptr->leftchild,child);if(p==nullptr){p=Parent(ptr->rightchild,child);}return p;}}<BtNode* FindParent(BtNode* ptr,BtNode* child){if(ptr==nullptr||child==nullptr||ptr==child){return nullptr;}else{return Parent(ptr,child);}}
这段代码定义了两个用于查找二叉树节点直接双亲的函数。Parent函数接收两个节点指针:当前节点ptr和待查找的子节点child。如果子节点child是ptr的左孩子或右孩子,则直接返回ptr作为双亲。若child不是左或右孩子,则递归调用Parent函数,继续向上查找。在递归结束时,如果未找到对应的双亲,则返回空指针。
FindParent函数则服务于更为简单的用途,它直接调用Parent函数来确定给定子节点child的直接双亲。该函数通过类似逻辑排除了一些无效情况,确保只返回有效的双亲节点。
转载地址:http://wtyiz.baihongyu.com/