ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

获取二进制中的完整节点数

前开发者教程 2020年10月8日

问题陈述:

给您一棵树的根节点,您需要找到该树中完整节点的数量。

如果一个节点同时具有左子节点和右子节点,则该节点将被视为完整节点。

考虑下图:

二元树

完整节点总数为3。

可以通过遍历树并保留同时具有左右子节点的节点数来解决此问题。

C ++解决方案

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};

 int get_full_node_count(struct Node* node) 
{ 
    if (node == NULL) 
       return 0; 
   
    int result = 0; 
    if  (node->left && node->right)  
       result++; 
   
    result += (get_full_node_count(node->left) +  
            get_full_node_count(node->right)); 

    return result; 
} 
 

int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              16
            /   \
           /     \
          10      25
         /  \    /  \
        /    \  /    \
       7    15 18     30

    */

    root = new Node(16);
    root->left = new Node(10);
    root->right = new Node(25);
    root->left->left = new Node(7);
    root->left->right = new Node(15);
    root->right->left = new Node(18);
    root->right->right = new Node(30);

    cout<<"Total number of full nodes are "<<get_full_node_count(root)<<endl;

    return 0;  
}

输出:

Total number of full nodes are 3

 

分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的

      <nav id="LceevIK" class="LIonDnr"><sup id="RtHzo4O"><code class="quwErnK"></code></sup></nav>


          <tbody id="MTfJGjk" class="M2rI8pV"><param class="xhRv2xo"><article id="ijaKyfu" class="ik8JT7C"></article></param></tbody><i id="WDpmLTK" class="WfgRlkh"><mark id="RuCynSn"></mark></i>