📜  计算二叉树中的完整节点(迭代和递归)

📅  最后修改于: 2022-05-13 01:57:16.922000             🧑  作者: Mango

计算二叉树中的完整节点(迭代和递归)

给定一棵二叉树,如何在不使用递归和递归的情况下计算所有完整节点(两个子节点都不是 NULL 的节点)?注意叶子不应该被触摸,因为它们的两个孩子都为 NULL。

节点 2 和 6 是完整节点,有两个子节点。所以上述树中的完整节点数为 2

方法:迭代
这个想法是使用水平顺序遍历来有效地解决这个问题。

1) Create an empty Queue Node and push root node to Queue.
2) Do following while nodeQeue is not empty.
   a) Pop an item from Queue and process it.
      a.1) If it is full node then increment count++.
   b) Push left child of popped item to Queue, if available.
   c) Push right child of popped item to Queue, if available.

下面是这个想法的实现。

C++
// C++ program to count
// full nodes in a Binary Tree
#include 
using namespace std;
 
// A binary tree Node has data, pointer to left
// child and a pointer to right child
struct Node
{
    int data;
    struct Node* left, *right;
};
 
// Function to get the count of full Nodes in
// a binary tree
unsigned int getfullCount(struct Node* node)
{
    // If tree is empty
    if (!node)
        return 0;
    queue q;
     
    // Do level order traversal starting from root
    int count = 0; // Initialize count of full nodes
    q.push(node);
    while (!q.empty())
    {
        struct Node *temp = q.front();
        q.pop();
 
        if (temp->left && temp->right)
            count++;
             
        if (temp->left != NULL)
            q.push(temp->left);
        if (temp->right != NULL)
            q.push(temp->right);
    }
    return count;
}
 
/* Helper function that allocates a new Node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
 
// Driver program
int main(void)
{
    /* 2
     / \
    7     5
    \     \
     6     9
    / \ /
    1 11 4
    Let us create Binary Tree as shown
    */
     
    struct Node *root = newNode(2);
    root->left     = newNode(7);
    root->right     = newNode(5);
    root->left->right = newNode(6);
    root->left->right->left = newNode(1);
    root->left->right->right = newNode(11);
    root->right->right = newNode(9);
    root->right->right->left = newNode(4);
     
    cout << getfullCount(root);
     
    return 0;
}


Java
// Java program to count
// full nodes in a Binary Tree
// using Iterative approach
import java.util.Queue;
import java.util.LinkedList;
 
// Class to represent Tree node
class Node
{
    int data;
    Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = null;
        right = null;
    }
}
 
// Class to count full nodes of Tree
class BinaryTree
{
 
    Node root;
 
    /* Function to get the count of full Nodes in
    a binary tree*/
    int getfullCount()
    {
        // If tree is empty
        if (root==null)
        return 0;
         
        // Initialize empty queue.
        Queue queue = new LinkedList();
         
        // Do level order traversal starting from root
        queue.add(root);
         
        int count=0; // Initialize count of full nodes
        while (!queue.isEmpty())
        {
 
            Node temp = queue.poll();
            if (temp.left!=null && temp.right!=null)
            count++;
 
            // Enqueue left child
            if (temp.left != null)
            {
                queue.add(temp.left);
            }
 
            // Enqueue right child
            if (temp.right != null)
            {
                queue.add(temp.right);
            }
        }
        return count;
    }
 
    public static void main(String args[])
    {
        /* 2
          / \
        7     5
        \     \
        6     9
        / \ /
        1 11 4
        Let us create Binary Tree as shown
        */
        BinaryTree tree_level = new BinaryTree();
        tree_level.root = new Node(2);
        tree_level.root.left = new Node(7);
        tree_level.root.right = new Node(5);
        tree_level.root.left.right = new Node(6);
        tree_level.root.left.right.left = new Node(1);
        tree_level.root.left.right.right = new Node(11);
        tree_level.root.right.right = new Node(9);
        tree_level.root.right.right.left = new Node(4);
 
        System.out.println(tree_level.getfullCount());
         
    }
}


Python3
# Python program to count
# full nodes in a Binary Tree
# using iterative approach
 
# A node structure
class Node:
    # A utility function to create a new node
    def __init__(self ,key):
        self.data = key
        self.left = None
        self.right = None
 
# Iterative Method to count full nodes of binary tree
def getfullCount(root):
    # Base Case
    if root is None:
        return 0
     
    # Create an empty queue for level order traversal
    queue = []
 
    # Enqueue Root and initialize count
    queue.append(root)
         
    count = 0 #initialize count for full nodes
    while(len(queue) > 0):
        node = queue.pop(0)
 
        # if it is full node then increment count
        if node.left is not None and node.right is not None:
            count = count+1
 
        # Enqueue left child
        if node.left is not None:
            queue.append(node.left)
 
        # Enqueue right child
        if node.right is not None:
            queue.append(node.right)
             
    return count
 
# Driver Program to test above function
root = Node(2)
root.left = Node(7)
root.right = Node(5)
root.left.right = Node(6)
root.left.right.left = Node(1)
root.left.right.right = Node(11)
root.right.right = Node(9)
root.right.right.left = Node(4)
 
 
print(getfullCount(root))


C#
// C# program to count
// full nodes in a Binary Tree
// using Iterative approach
using System;
using System.Collections.Generic;
 
// Class to represent Tree node
public class Node
{
    public int data;
    public Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = null;
        right = null;
    }
}
 
// Class to count full nodes of Tree
public class BinaryTree
{
 
    Node root;
 
    /* Function to get the count of full Nodes in
    a binary tree*/
    int getfullCount()
    {
        // If tree is empty
        if (root == null)
        return 0;
         
        // Initialize empty queue.
        Queue queue = new Queue();
         
        // Do level order traversal starting from root
        queue.Enqueue(root);
         
        int count = 0; // Initialize count of full nodes
        while (queue.Count != 0)
        {
 
            Node temp = queue.Dequeue();
            if (temp.left != null && temp.right != null)
            count++;
 
            // Enqueue left child
            if (temp.left != null)
            {
                queue.Enqueue(temp.left);
            }
 
            // Enqueue right child
            if (temp.right != null)
            {
                queue.Enqueue(temp.right);
            }
        }
        return count;
    }
 
    // Driver code
    public static void Main(String []args)
    {
        /* 2
        / \
        7 5
        \ \
        6 9
        / \ /
        1 11 4
        Let us create Binary Tree as shown
        */
        BinaryTree tree_level = new BinaryTree();
        tree_level.root = new Node(2);
        tree_level.root.left = new Node(7);
        tree_level.root.right = new Node(5);
        tree_level.root.left.right = new Node(6);
        tree_level.root.left.right.left = new Node(1);
        tree_level.root.left.right.right = new Node(11);
        tree_level.root.right.right = new Node(9);
        tree_level.root.right.right.left = new Node(4);
 
        Console.WriteLine(tree_level.getfullCount());
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript


C++
// C++ program to count full nodes in a Binary Tree
#include 
using namespace std;
  
// A binary tree Node has data, pointer to left
// child and a pointer to right child
struct Node
{
    int data;
    struct Node* left, *right;
};
  
// Function to get the count of full Nodes in
// a binary tree
unsigned int getfullCount(struct Node* root)
{
    if (root == NULL)
       return 0;
  
    int res = 0;
    if  (root->left && root->right)
       res++;
  
    res += (getfullCount(root->left) +
            getfullCount(root->right));
    return res;
}
  
/* Helper function that allocates a new
   Node with the given data and NULL left
   and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
// Driver program
int main(void)
{
    /* 2
     / \
    7    5
    \    \
     6   9
    / \ /
    1 11 4
    Let us create Binary Tree as shown
    */
  
    struct Node *root = newNode(2);
    root->left    = newNode(7);
    root->right   = newNode(5);
    root->left->right = newNode(6);
    root->left->right->left = newNode(1);
    root->left->right->right = newNode(11);
    root->right->right = newNode(9);
    root->right->right->left = newNode(4);
  
    cout << getfullCount(root);
  
    return 0;
}


Java
// Java program to count full nodes in a Binary Tree
import java.util.*;
class GfG {
 
// A binary tree Node has data, pointer to left
// child and a pointer to right child
static class Node
{
    int data;
    Node left, right;
}
 
// Function to get the count of full Nodes in
// a binary tree
static int getfullCount(Node root)
{
    if (root == null)
    return 0;
 
    int res = 0;
    if (root.left != null && root.right != null)
    res++;
 
    res += (getfullCount(root.left) + getfullCount(root.right));
    return res;
}
 
/* Helper function that allocates a new
Node with the given data and NULL left
and right pointers. */
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    return (node);
}
 
// Driver program
public static void main(String[] args)
{
    /* 2
    / \
    7 5
    \ \
    6 9
    / \ /
    1 11 4
    Let us create Binary Tree as shown
    */
 
    Node root = newNode(2);
    root.left = newNode(7);
    root.right = newNode(5);
    root.left.right = newNode(6);
    root.left.right.left = newNode(1);
    root.left.right.right = newNode(11);
    root.right.right = newNode(9);
    root.right.right.left = newNode(4);
 
    System.out.println(getfullCount(root));
 
}
}


Python3
# Python program to count full
# nodes in a Binary Tree
class newNode():
 
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
         
         
# Function to get the count of 
# full Nodes in a binary tree
def getfullCount(root):
 
    if (root == None):
        return 0
     
    res = 0
    if (root.left and root.right):
        res += 1
     
    res += (getfullCount(root.left) +
            getfullCount(root.right))
    return res
 
         
# Driver code
if __name__ == '__main__':
    """ 2
    / \
    7 5
    \ \
    6 9
    / \ /
    1 11 4
    Let us create Binary Tree as shown
    """
     
    root = newNode(2)
    root.left = newNode(7)
    root.right = newNode(5)
    root.left.right = newNode(6)
    root.left.right.left = newNode(1)
    root.left.right.right = newNode(11)
    root.right.right = newNode(9)
    root.right.right.left = newNode(4)
     
    print(getfullCount(root))
 
# This code is contributed by SHUBHAMSINGH10


C#
// C# program to count full nodes in a Binary Tree
using System;
 
class GfG
{
 
// A binary tree Node has data, pointer to left
// child and a pointer to right child
public class Node
{
    public int data;
    public Node left, right;
}
 
// Function to get the count of full Nodes in
// a binary tree
static int getfullCount(Node root)
{
    if (root == null)
    return 0;
 
    int res = 0;
    if (root.left != null && root.right != null)
    res++;
 
    res += (getfullCount(root.left) + getfullCount(root.right));
    return res;
}
 
/* Helper function that allocates a new
Node with the given data and NULL left
and right pointers. */
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    return (node);
}
 
// Driver program
public static void Main()
{
    /* 2
    / \
    7 5
    \ \
    6 9
    / \ /
    1 11 4
    Let us create Binary Tree as shown
    */
 
    Node root = newNode(2);
    root.left = newNode(7);
    root.right = newNode(5);
    root.left.right = newNode(6);
    root.left.right.left = newNode(1);
    root.left.right.right = newNode(11);
    root.right.right = newNode(9);
    root.right.right.left = newNode(4);
 
    Console.WriteLine(getfullCount(root));
}
}
 
/* This code contributed by PrinciRaj1992 */


Javascript


输出:

2

时间复杂度: O(n)
辅助空间: O(n) 其中,n 是给定二叉树中的节点数

方法:递归
这个想法是按后序遍历树。如果当前节点已满,我们将结果加 1 并添加左右子树的返回值。

C++

// C++ program to count full nodes in a Binary Tree
#include 
using namespace std;
  
// A binary tree Node has data, pointer to left
// child and a pointer to right child
struct Node
{
    int data;
    struct Node* left, *right;
};
  
// Function to get the count of full Nodes in
// a binary tree
unsigned int getfullCount(struct Node* root)
{
    if (root == NULL)
       return 0;
  
    int res = 0;
    if  (root->left && root->right)
       res++;
  
    res += (getfullCount(root->left) +
            getfullCount(root->right));
    return res;
}
  
/* Helper function that allocates a new
   Node with the given data and NULL left
   and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
// Driver program
int main(void)
{
    /* 2
     / \
    7    5
    \    \
     6   9
    / \ /
    1 11 4
    Let us create Binary Tree as shown
    */
  
    struct Node *root = newNode(2);
    root->left    = newNode(7);
    root->right   = newNode(5);
    root->left->right = newNode(6);
    root->left->right->left = newNode(1);
    root->left->right->right = newNode(11);
    root->right->right = newNode(9);
    root->right->right->left = newNode(4);
  
    cout << getfullCount(root);
  
    return 0;
}

Java

// Java program to count full nodes in a Binary Tree
import java.util.*;
class GfG {
 
// A binary tree Node has data, pointer to left
// child and a pointer to right child
static class Node
{
    int data;
    Node left, right;
}
 
// Function to get the count of full Nodes in
// a binary tree
static int getfullCount(Node root)
{
    if (root == null)
    return 0;
 
    int res = 0;
    if (root.left != null && root.right != null)
    res++;
 
    res += (getfullCount(root.left) + getfullCount(root.right));
    return res;
}
 
/* Helper function that allocates a new
Node with the given data and NULL left
and right pointers. */
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    return (node);
}
 
// Driver program
public static void main(String[] args)
{
    /* 2
    / \
    7 5
    \ \
    6 9
    / \ /
    1 11 4
    Let us create Binary Tree as shown
    */
 
    Node root = newNode(2);
    root.left = newNode(7);
    root.right = newNode(5);
    root.left.right = newNode(6);
    root.left.right.left = newNode(1);
    root.left.right.right = newNode(11);
    root.right.right = newNode(9);
    root.right.right.left = newNode(4);
 
    System.out.println(getfullCount(root));
 
}
}

Python3

# Python program to count full
# nodes in a Binary Tree
class newNode():
 
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
         
         
# Function to get the count of 
# full Nodes in a binary tree
def getfullCount(root):
 
    if (root == None):
        return 0
     
    res = 0
    if (root.left and root.right):
        res += 1
     
    res += (getfullCount(root.left) +
            getfullCount(root.right))
    return res
 
         
# Driver code
if __name__ == '__main__':
    """ 2
    / \
    7 5
    \ \
    6 9
    / \ /
    1 11 4
    Let us create Binary Tree as shown
    """
     
    root = newNode(2)
    root.left = newNode(7)
    root.right = newNode(5)
    root.left.right = newNode(6)
    root.left.right.left = newNode(1)
    root.left.right.right = newNode(11)
    root.right.right = newNode(9)
    root.right.right.left = newNode(4)
     
    print(getfullCount(root))
 
# This code is contributed by SHUBHAMSINGH10

C#

// C# program to count full nodes in a Binary Tree
using System;
 
class GfG
{
 
// A binary tree Node has data, pointer to left
// child and a pointer to right child
public class Node
{
    public int data;
    public Node left, right;
}
 
// Function to get the count of full Nodes in
// a binary tree
static int getfullCount(Node root)
{
    if (root == null)
    return 0;
 
    int res = 0;
    if (root.left != null && root.right != null)
    res++;
 
    res += (getfullCount(root.left) + getfullCount(root.right));
    return res;
}
 
/* Helper function that allocates a new
Node with the given data and NULL left
and right pointers. */
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    return (node);
}
 
// Driver program
public static void Main()
{
    /* 2
    / \
    7 5
    \ \
    6 9
    / \ /
    1 11 4
    Let us create Binary Tree as shown
    */
 
    Node root = newNode(2);
    root.left = newNode(7);
    root.right = newNode(5);
    root.left.right = newNode(6);
    root.left.right.left = newNode(1);
    root.left.right.right = newNode(11);
    root.right.right = newNode(9);
    root.right.right.left = newNode(4);
 
    Console.WriteLine(getfullCount(root));
}
}
 
/* This code contributed by PrinciRaj1992 */

Javascript


输出:

2

时间复杂度: O(n)
辅助空间: O(n)

其中,n 是给定二叉树中的节点数

类似文章:

  • 计算二叉树中的一半节点(迭代和递归)
  • 获取二叉树中叶节点数量的程序
  • 给定一棵二叉树,如何删除所有半节点?
  • 打印二叉树中的所有完整节点