美文网首页
完全二叉树

完全二叉树

作者: 小王同学加油 | 来源:发表于2019-02-18 18:10 被阅读73次

题目 完全二叉树

image.png

分析

image.png

答案

//完全二叉树:

/**

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);

}

相关文章

  • 958. 二叉树的完全性检验

    判断是否是完全二叉树 给定一个二叉树,确定它是否是一个完全二叉树。 百度百科中对完全二叉树的定义如下: 若设二叉树...

  • 222. 完全二叉树的节点个数

    222. 完全二叉树的节点个数 给出一个完全二叉树,求出该树的节点个数。 说明: 完全二叉树的定义如下:在完全二叉...

  • 完全二叉树实现优先队列与堆排序

    本文的目标是要做出优先队列和堆排序两个Demo。 完全二叉树 优先队列 堆排序 完全二叉树 完全二叉树的定义是建立...

  • 完全二叉树的节点个数

    给出一个完全二叉树,求出该树的节点个数。 说明: [完全二叉树]定义如下:在完全二叉树中,除了最底层节点可能没填满...

  • 222. Count Complete Tree Nodes

    完全二叉树的节点的个数。 给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。 完全二叉树 的定义如下...

  • 222. 完全二叉树的节点个数

    给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。 完全二叉树 的定义如下:在完全二叉树中,除了最底...

  • LeetCode-222-完全二叉树的节点个数

    完全二叉树的节点个数 题目描述:给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。完全二叉树 的定义...

  • 认识二叉堆

    什么是二叉堆? 二叉堆本质上是一种完全二叉树( 完全二叉树是效率很高的数据结构,完全二叉树是由满二叉树而引...

  • 二叉(搜索)树转换/完全二叉树验证解析

    1.二叉树完全性检验(958-中) 题目描述:给定一个二叉树,确定它是否是一个完全二叉树。百度百科中对完全二叉树的...

  • [AlgoGo]堆

    堆的定义 完全二叉树 每个节点大于等于子节点 堆的实现 存储方式堆是一个完全二叉树,完全二叉树适合时候数组存储,因...

网友评论

      本文标题:完全二叉树

      本文链接:https://www.haomeiwen.com/subject/dkdzeqtx.html