代码之家  ›  专栏  ›  技术社区  ›  flopex

如何计算二叉树中的正确子代数?

  •  2
  • flopex  · 技术社区  · 16 年前

    如何计算二叉树中的正确子代数?

    这意味着我只希望孩子们被标记为正确的。

    前任。

    (Left | Right)
    
          F(Root)    
      G   |   H     
    T   U |  I  J  
    

    正确的孩子应该是U、H和J。

    找到这些的算法是什么?

    5 回复  |  直到 10 年前
        1
  •  6
  •   zs2020    16 年前
    int count(Tree *r){
        if(r == NULL) return 0;
        int num_l=0, num_r=0;
        if(r->left != NULL) 
            num_l = count(r->left);
        if(r->right != NULL) 
            num_r = count(r->right)+1;
        return num_l+num_r
    }
    
        2
  •  1
  •   Kuba Tyszko    16 年前

    在递归方法中,

    您将调用一个函数来遍历树, 对于当前节点,您需要: 检查当前节点是否有正确的子节点(然后递增计数器),然后为正确的节点递归调用函数。 检查当前节点是否有左子节点,对于左节点递归调用函数。

    这应该有效。

        3
  •  1
  •   duduamar    16 年前

    在树上执行简单的遍历(即按顺序执行后序),如果每个节点都有正确的子节点,则对其执行+1。

    示例(没有尝试编译和检查它):

    int countRightChildren(Node root)
    {
       if (root == null) return 0;
       int selfCount =  (root.getRightChild() != null) ? 1 : 0;
       return selfCount + countRightChildren(root.getLeftChild()) + countRightChildren(root.getRightChild());
    }
    
        4
  •  0
  •   codaddict    16 年前

    您可以递归地这样做:

    • 如果树不存在,就没有 孩子们。
    • 如果存在树,则r子级 = γ r子树中的r子代 + 阿尔 L-子树中的子代

    .

      int countRChildren(Node *root) {
            if(!root)  // tree does not exist.
                return 0;
    
            // tree exists...now see if R node exits or not.
            if(root->right) // right node exist
    
                // return 1 + # of R children in L/R subtree.
                return 1 + countRChildren(root->right) + countRChildren(root->left);
    
            else // right nodes does not exist.
                // total count of R children will come from left subtree.
                return countRChildren(root->left);
        }
    
        5
  •  0
  •   Baselyos    10 年前

    这包括我如何构建结构

     struct Item
     {
       int info;
       struct Item* right;
       struct Item* left;
     };
     typedef struct Item* Node;
    
    int countRightSons(Node tree)
    {
      if(!tree)
        return 0;
      if(tree->right != NULL)
        return 1 + countRightSons(tree->right) + countRightSons(tree->left);
       return countRightSons(tree->left);
    }