Number of K-level nodes and two tree leaf nodes in 6:2-fork Tree

Source: Internet
Author: User

two fork tree in the first k number of Layer nodes


Recursive solution:

(1) If the binary tree is empty or k<1 returns 0

(2) If the binary tree is not empty and k==1, return 1

(3) If the binary tree is not empty and k>1, the number of nodes in the record k-1 layer and the number of nodes in the right subtree k-1 layer are returned.


The code is as follows:

int Getnodenumkthlevel (Binarytreenode *proot, int k)

{

if (proot = = NULL | | K < 1)

return 0;

if (k = = 1)

return 1;


int numleft = Getnodenumkthlevel (Proot->m_pleft, k-1); Record number of nodes in K-1 layer

int numright = Getnodenumkthlevel (Proot->m_pright, k-1); Number of nodes in the K-1 layer in the right sub-tree

Return (Numleft + numright);

}


Number of leaf nodes in binary tree


Recursive mode

(1) If the given node proot is null, then it is an empty tree, the leaf node is 0 and returns 0;

(2) if the given node proot the left and right subtree are null, then the leaf node, and the number of leaf nodes is 1, return 1;

(3) if the given node proot the left and right subtree is not all null, it is not a leaf node, proot as the root node of the subtree of the number of leaf nodes =proot Yeko the number of nodes +proot the leaf section of the tree

The code is as follows

int Getleafnum (Binarytreenode *proot)

{

if (Proot ==null)

Return0;

if (Proot->m_pleft = = NULL && Proot->m_pright = = null)

RETURN1;

Return (Getleafnum (proot->m_pleft) + getleafnum (proot->m_pright));

}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Number of K-level nodes and two tree leaf nodes in 6:2-fork Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.