我需要设计一个算法来返回二叉树中有两个子节点的节点数

时间:2017-04-29 12:02:32

标签: algorithm data-structures

我遇到过这个问题,设计了一个算法来计算二元树中有两个子节点的节点数。有人提到解决方案应该表示为一对函数(不是BST成员函数)。

到目前为止,我无法找到具体的解决方案,特别是解决方案应该被表达为一对非BST成员函数的部分正在我脑海中浮现。

3 个答案:

答案 0 :(得分:1)

//count the number of node that has got 2 children   
 function countNodes(nodeElement,nodeNumber){
    var nodeNumber = 0;
    var children = nodeElement.children;
    for(var c=0;c<children ;c++){
    //check if current node has got two childs
      if(getNodeChildren(children[c])==2){
          nodeNumber++;
      }
     //recursively check if children nodes has got 2 children 
      nodeNumber += countNodes(children[c],nodeNumber)
    }
    return nodeNumber;  
    }

 //recursively counts the number of children that a node has got
function getNodeChildren(nodeElement){
//check if is a leaf
if(nodeElement.children == 0){
   return 1;
}
else {
  var nodeNumber = 0;
  var children = nodeElement.children;
  for(var c=0;c<children ;c++){
    nodeNumber += getNodeChildren(children[c],nodeNumber+1);
  }
return nodeNumber;
}

}

答案 1 :(得分:1)

假设Nodestruct,其中包含指向Node的两个指针,名为leftright

int count_2_ch_nodes(Node* root)
{
    if (root == NULL) return 0;
    // Recursively count the number of nodes that are below
    // this node that have two children:
    int count = 0;
    if (root->left != NULL) count += count_2_ch_nodes(root->left);
    if (root->right != NULL) count += count_2_ch_nodes(root->right);
    // Add this node IF it has 2 children:
    if (has_2_ch(root)) count++;
    return count;
}

/* Returns TRUE if node has two children */
int has_2_ch(Node* node)
{
    return (node->left != NULL && node->right != NULL);
}

答案 2 :(得分:0)

这是您的问题的完整Java代码。

import java.util.ArrayList;
import java.util.Scanner;


/*
*  Creating datastructure for Node
*  Every Node contains data given by user and leftChild and rightChild childs
*  Left and rightChild childs are automatically assigned by the program
*/
class Node
{
    Node leftChild, rightChild;
    String data;

    /*
     *  Assigning leftChild , rightChild and data to the node using a constructor
     */

    Node(Node left, Node right, String data)
    {
        this.leftChild =left;
        this.rightChild =right;
        this.data=data;
    }

}
public class FirstAnswer {
    /*
     * Initializing the count for number of nodes
     */
    private static int count=0;
    private static int numberOfNodes(Node root)
    {

        /*
         * Writing the base case for the recursive function
         * If leftChild or rightChild or both are null it returns 0 as no childs are present
         */

        if ((root.leftChild ==null && root.rightChild ==null) || (root.leftChild ==null) || (root.rightChild ==null))
            return 0;

        else {

            count+=2;
            Node left=root.leftChild;
            Node right=root.rightChild;

            /*
             *  Calling the recursive function twice by making leftChild child and rightChild child of root as root
             */

            System.out.println(root.data+" : "+"\n"+"Left child : "+left.data+"\n"+"Right child : "+right.data);
            numberOfNodes(left);
            numberOfNodes(right);

        }
        return count+1; //Since root node is not counted
    }
    public static void main(String... args)
    {
        Scanner sc=new Scanner(System.in);

        /*
         *  Creating individual nodes with string data from user
         *  Holding them in an array list inputs
         */

        ArrayList<Node> inputs=new ArrayList<>();
        String status="Y";
        System.out.print("Enter data for root node : ");
        inputs.add(new Node(null,null,sc.next()));
        while (status.equals("Y") || status.equals("y"))
        {
            if (inputs.size()%2==1)
            {
                for (int j=0;j<2;j++)
                {
                    System.out.print("data for child "+(j+1)+" : ");
                    inputs.add(new Node(null,null,sc.next()));
                }

                /*
                 *  Yes or No for adding more number of nodes
                 */

                System.out.println("Press Y or y if more inputs have to be given else press N to construct tree with given inputs...");
                status=sc.next();
            }
        }
        Node[] tree=new Node[inputs.size()];
        /*
         *   Above is the tree which is being constructed from the nodes given by user
         */
        for (int i=inputs.size()-1;i>=0;i--)
        {
            int j=i+1;
            /*
             *   Making tree format by locating childs with indices at 2*p and 2*p+1
             */

            if ((2*j+1)<=inputs.size())
            {
                tree[i]=new Node(tree[2*i+1],tree[2*i+2],inputs.get(i).data);
            }
            else {
                tree[i]=inputs.get(i);
            }

        }

        /*
         *   Calling the recursive function to count number of nodes
         *   Since first node is the root we start from here
         */

        System.out.println(numberOfNodes(tree[0]));
    }
}

希望这可以帮助你;)