检查二叉树中的子项和属性

时间:2013-09-17 06:09:24

标签: c binary-tree

Childer Sum属性表示对于每个节点,数据值必须等于左右子节点中数据值的总和。 我已经实现了一个递归函数,它检查二叉树是否满足该属性。但是代码为每棵树返回1。 请帮忙告诉逻辑是否有问题? :) 这是函数

   int child_sum(struct tree *node)

    {
      if(node==NULL)
        {
          return 0;

       }

if(node->left!=NULL && node->right!=NULL)
        {
      if(node->data=node->left->data+node->right->data)
      {
      return 1;
        }
       }

  return child_sum(node->left) && child_sum(node->right);
}

2 个答案:

答案 0 :(得分:0)

if(node->data=node->left->data+node->right->data)应为if(node->data==node->left->data+node->right->data)

注意==。在你的情况下,它是赋值(=),它始终是真的。

答案 1 :(得分:0)

这是我对包含childrenSum方法的二叉树的实现。

struct BTree
{
    struct NodeTree
    {
        NodeTree (int in) : data(in) { left = nullptr; right = nullptr;}
        NodeTree* left;
        NodeTree* right;
        int data;
    };

    NodeTree* head;


    BTree(std::initializer_list<int> inList)
    {
        head = nullptr;
        for (auto elem : inList)
        {
            NodeTree* nodeTree = new NodeTree(elem);
            insert(nodeTree);
        }
    }

    void insert( NodeTree* newElem )
    {
        if (head == nullptr)
        {
            head = newElem;
            return;
        }
        insert2End(head, newElem);
    }

    void insert2End( NodeTree* current, NodeTree* newElem )
    {
        std::deque<NodeTree*> queue;
        queue.push_back(current);
        NodeTree* lastElem = nullptr;
        while (!queue.empty())
        {
            lastElem = queue.front();
            queue.pop_front();
            if (lastElem->left)
                queue.push_back(lastElem->left);
            else
            {
                lastElem->left = newElem;
                break;
            }

            if (lastElem->right)
                queue.push_back(lastElem->right);
            else
            {
                lastElem->right = newElem;
                break;
            }
        }
    }


    int postOrderTreeTraverser(NodeTree* in)
    {
        int totalSum = 0;
        if (in->left)
            totalSum += postOrderTreeTraverser(in->left);
        if (in->right)
            totalSum += postOrderTreeTraverser(in->right);

        int returnVal = in->data;
        if (in->left != nullptr || in->right != nullptr )
            in->data = totalSum;

        return returnVal;

    }



    void childrenSum()
    {
        if (head == nullptr)
        {
            return;
        }
        postOrderTreeTraverser(head);
    }

};