问题陈述:
给您一棵树的根节点,您需要找到该树中完整节点的数量。
如果一个节点同时具有左子节点和右子节点,则该节点将被视为完整节点。
考虑下图:
完整节点总数为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