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_non_leaf_node_count(struct Node* node) 
{ 
    // Base cases. 
    if (node == NULL || (node->left == NULL &&  
                         node->right == NULL)) 
        return 0; 
  
    return 1 + get_non_leaf_node_count(node->left) +  
               get_non_leaf_node_count(node->right); 
} 


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 Non leaf nodes are "<<get_non_leaf_node_count(root)<<endl;

    return 0;  
} 

输出:

Total number of Non leaf nodes are 3
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

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

发表评论

取消回复

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的
<bdi class="HXoo6jC"><wbr id="fTOuWSb"><blockquote id="tqLaQhl" class="t2lyNfj"></blockquote></wbr></bdi>
  • <sub id="JenURpG"></sub>
    <time id="vTtISX0" class="vQwyiW5"><hr id="QnrgaVa"></hr></time>

    <q id="gL6uX73" class="gG9oUxK"></q>






          • <a id="lXXAYDk"></a>

              <table class="s0u2qhX"><section id="P9ZmVwc"><textarea class="nlc5I2N"><thead id="oeE9587"></thead></textarea></section></table>

              <abbr id="fzfEFPp"></abbr>