二叉树的操作
-
树中节点的数目
int Size(bt_node *ptr) // 树中所有节点的数目 { if(ptr == NULL) return 0; else return 1+Size(ptr->leftchild)+Size(ptr->rightchild); } int SizeLeaf(bt_node *ptr) // 树中叶子节点的数目 { if(ptr == NULL) return 0; else if(ptr->leftchild == NULL && ptr->rightchild == NULL) { return 1; }else { return SizeLeaf(ptr->leftchild)+SizeLeaf(ptr->rightchild); } } int SizeOneBranch(bt_node *ptr) // 树中单分支节点的数目 { if(ptr == NULL) return 0; else if((ptr->leftchild != NULL && ptr->rightchild == NULL)||ptr->leftchild == NULL && ptr->rightchild != NULL)) { return 1; }else { return SizeLeaf(ptr->leftchild)+SizeLeaf(ptr->rightchild); } } int SizeTwoBranch(bt_node *ptr) // 树中双分支节点的数目 { if(ptr == NULL) return 0; else if(ptr->leftchild != NULL && ptr->rightchild != NULL) { return 1; }else { return SizeLeaf(ptr->leftchild)+SizeLeaf(ptr->rightchild); } } -
树的深度
int Max(int a,int b) { return a>b? a:b; } int Depth(bt_node *ptr) { if(ptr == NULL) { return 0; }else { return Max(Depth(ptr->leftchild),Depth(ptr->rightchild)) + 1; } } -
寻找父亲节点
bt_node * Parent(bt_node *ptr,bt_node *child) { if(ptr == NULL || ptr->leftchild == child || ptr->rightchild == child) { return ptr; }else { bt_node *p = Parent(ptr->leftchild,child); if(NULL == p) { p = Parent(ptr->rightchild,child); } return p; } } bt_node * FindParet(bt_node *ptr,bt_node *child) { if(ptr == NULL || child == NULL || ptr == child) { return NULL; }else { return Parent(ptr,child); } }
本文详细介绍了二叉树的各种操作,包括计算节点总数、叶子节点数、单分支节点数及双分支节点数的方法,并提供了计算树深度的递归算法。此外,还探讨了如何寻找指定节点的父亲节点。
2180

被折叠的 条评论
为什么被折叠?



