文章目录
- 一、二叉树的深度
- 二、二叉树的k层节点个数
- 三、二叉树的销毁
- 四、二叉树查找值为x的节点
一、二叉树的深度
int BTreeHeight(BTNode* root)
{if (root == NULL)return 0;int rightHeight = BTreeHeight(root->right);int leftHeight = BTreeHeight(root->left);return rightHeight > leftHeight ? rightHeight + 1 : leftHeight + 1;
}
int main()
{BTNode* node1 = BuySTNode(1);BTNode* node2 = BuySTNode(2);BTNode* node3 = BuySTNode(3);BTNode* node4 = BuySTNode(4);BTNode* node5 = BuySTNode(5);BTNode* node6 = BuySTNode(6);BTNode* node7 = BuySTNode(7);node1->left = node2;node1->right = node4;node2->right = node5;node2->left = node3;node4->left = node6;node4->right = node7;printf("%d", BTreeHeight(node1));return 0;
}
二、二叉树的k层节点个数
int BTreeLevelKSize(BTNode* root,int k)
{if (root==NULL)return 0;if (k == 1)return 1;return BTreeLevelKSize(root->left,k-1)+ BTreeLevelKSize(root->right, k - 1);
}
三、二叉树的销毁
熟悉了前面的递归,销毁递归基本上是小菜一碟,从最下面的节点开始销毁
void BTreeDistroy(BTNode* root)
{if (root == NULL)return;BTreeDistroy(root->left);BTreeDistroy(root->right);}
四、二叉树查找值为x的节点
BTNode* BTreeFind(BTNode* root,int x)
{if (root == NULL)return NULL;if (root->data == x)return root;BTNode* ret1 = BTreeFind(root->left,x);if (ret1->data == x)return ret1;BTNode* ret2 = BTreeFind(root->right,x);if (ret2->data == x)return ret2;return NULL;
}