赞
踩
- typedef int BTDataType;
- typedef struct BinaryTreeNode
- {
- BTDataType data;
- struct BinaryTreeNode* left;
- struct BinaryTreeNode* right;
- }TreeNode;
-
- TreeNode* BuyTreeNode(int x)
- {
- TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
- assert(node);
-
- node->data = x;
- node->left = NULL;
- node->right = NULL;
-
- return node;
- }
-
- TreeNode* CreateTree()
- {
- TreeNode* node1 = BuyTreeNode(1);
- TreeNode* node2 = BuyTreeNode(2);
- TreeNode* node3 = BuyTreeNode(3);
- TreeNode* node4 = BuyTreeNode(4);
- TreeNode* node5 = BuyTreeNode(5);
- TreeNode* node6 = BuyTreeNode(6);
- TreeNode* node7 = BuyTreeNode(7);
-
-
- node1->left = node2;
- node1->right = node4;
- node2->left = node3;
- node4->left = node5;
- node4->right = node6;
- node5->right = node7;
-
- return node1;
- }
- // 二叉树前序遍历
- void PrevOrder(TreeNode* root)
- {
- if (root == NULL)
- {
- printf("N ");
- return;
- }
- printf("%d ", root->data);
- PrevOrder(root->left);
- PrevOrder(root->right);
- }
- // 二叉树中序遍历
- void InOrder(TreeNode* root)
- {
- if (root == NULL)
- {
- printf("N ");
- return;
- }
- InOrder(root->left);
- printf("%d ", root->data);
- InOrder(root->right);
- }
- // 二叉树后序遍历
- void PostOrder(TreeNode* root)
- {
- if (root == NULL)
- {
- printf("N ");
- return;
- }
- PostOrder(root->left);
- PostOrder(root->right);
- printf("%d ", root->data);
- }
二叉树节点个数:
- // 二叉树节点个数
- int TreeSize(TreeNode* root)
- {
- return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
- }
- // 叶子节点的个数
- int TreeLeafSize(TreeNode* root)
- {
- // 空 返回0
- if (root == NULL)
- return 0;
- // 不是空,是叶子 返回1
- if (root->left == NULL
- && root->right == NULL)
- return 1;
-
- // 不是空 也不是叶子 分治=左右子树叶子之和
- return TreeLeafSize(root->left) +
- TreeLeafSize(root->right);
- }
二叉树的高度:
思路;
- //int TreeHeight(TreeNode* root)
- //{
- // if (root == NULL)
- // return 0;
- // int leftHeight = TreeHeight(root->left);
- // int rightHeight = TreeHeight(root->right);
- //
- // return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
- //}
-
- int TreeHeight(TreeNode* root)
- {
- if (root == NULL)
- return 0;
-
- return fmax(TreeHeight(root->left), TreeHeight(root->right)) + 1;
- }
二叉树第k层节点个数
思路:
代码:
- int TreeLevelK(TreeNode* root, int k)
- {
- assert(k > 0);
- if (root == NULL)
- return 0;
-
- if (k == 1)
- return 1;
-
- return TreeLevelK(root->left, k-1)
- + TreeLevelK(root->right, k-1);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。