前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >漫谈递归之完全二叉树

漫谈递归之完全二叉树

作者头像
程序员小王
发布2019-03-06 15:40:43
2810
发布2019-03-06 15:40:43
举报
文章被收录于专栏:架构说架构说

题目 完全二叉树

答案

//完全二叉树:

/**

1 Calculate the number of nodes (count) in the binary tree.

2 Start recursion of the binary tree from the root node of the binary tree with index (i) being set as 0 and the number of nodes in the binary (count).

3 If the current node under examination is NULL, then the tree is a complete binary tree. Return true.

4 If index (i) of the current node is greater than or equal to the number of nodes in the binary tree (count) i.e. (i>= count), then the tree is not a complete binary. Return false.

5 Recursively check the left and right sub-trees of the binary tree for same condition. 

For the left sub-tree use the index as (2*i + 1) while for the right sub-tree use the index as (2*i + 2).

6 The time complexity of the above algorithm is O(n). 

**/

bool isCompleteBinary(node *root)

{

    int total=isCompleteBinary(root);

   return is_complete_binary(root,1,total);



}

bool is_complete_binary(node *root,int index,int& length)

{

   if(root ==NULL)

   {

      return true;

   }

   if(index>length)

   {

     return false;

   }

  return  is_complete_binary(root->left,2*index,length) && is_complete_binary(root->right,2*index+1,length);

}

int get_node_number(node* root)

{

    if(root ==NULL)

    {

        return 0;

    }



    return 1+get_node_number(root->left)+get_node_number(root->right);

}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-02-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Offer多多 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 答案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档