- 转自:http://blog.csdn.net/randyjiawenjie/article/details/6329712
- void insert(tNode root,int data)
- {
- tNode newNode = (tNode)malloc(sizeof(treeNode));
- newNode->data = data;
- newNode->lchild = NULL;
- newNode->rchild = NULL;
- tNode current = root;
- tNode parent;
- while (1)
- {
- parent = current;
- if (current->data > newNode->data)
- {
- current = current->lchild;
- if (current == NULL)
- {
- parent->lchild = newNode;
- return;
- }
- }
- else
- {
- current = current->rchild;
- if (current == NULL)
- {
- parent->rchild = newNode;
- return;
- }
- }
- }
- }
- /**
- * 递归中序遍历二叉树
- */
- void preOrder(tNode root)
- {
- if (root != NULL)
- {
- preOrder(root->lchild);
- printf("%d ",root->data);
- preOrder(root->rchild);
- }
- }
- /**
- * 求二叉树叶子节点数目
- */
- int getLeaf(tNode root)
- {
- if (root == NULL)
- return 0;
- else
- if (root->lchild == NULL && root->rchild == NULL)
- return 1;
- else
- return getLeaf(root->lchild) + getLeaf(root->rchild);
- }
- /**
- * 求二叉树的深度
- */
- int getDepth(tNode root)
- {
- if (root == NULL)
- return 0;
- else
- return getDepth(root->lchild) > getLeaf(root->rchild)? 1 + getDepth(root->lchild): 1 + getDepth(root->rchild);
- // {
- // int depthLchild = 1 + getDepth(root->lchild);
- // int depthRchild = 1 + getDepth(root->rchild);
- // return depthLchild > depthRchild ? depthLchild: depthRchild;
- // }
- }
- int main()
- {
- tNode root = (tNode)malloc(sizeof(treeNode));
- root->data = 10;
- root->lchild = NULL;
- root->rchild = NULL;
- // insert(root,10);
- insert(root,5);
- insert(root,15);
- insert(root,1);
- insert(root,8);
- insert(root,20);
- insert(root,12);
- preOrder(root);
- printf("/n");
- int numleaf = getLeaf(root);
- printf("%d/n", numleaf);
- int depth = getDepth(root);
- printf("%d/n",depth);
- return 0;
- }
二叉树的基本操作
最新推荐文章于 2024-01-03 03:09:29 发布