检查二叉树是否为和树

时间:2015-02-22 14:35:41

标签: binary-tree

方法:

1)如果节点是叶节点,那么以该节点为根的子树的总和等于该节点的值。

2)如果节点不是叶子节点,那么以该节点为根的子树的总和是该节点值的两倍(假设以该节点为根的树是SumTree)。

[链接] http://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/

Qstn:为什么我们需要在它是叶子节点时初始化ls = 0或rs = 0。考虑链接中给出的树,如果我们到达节点4 if(node == NULL || isLeaf(node)) 返回1; 上面的代码返回1(true)回到它被调用的函数,即节点10类似地右侧将true返回到节点10,所以我们现在可以进入下面的循环,因为两个条件都为真 if(isSumTree(node-> left)&& isSumTree(node-> right)) 如果节点为10,我们计算左边和右边的数据,如果在条件中给出,那么为什么条件if(node-> left == NULL)然后ls = 0必要(isn' t已经照顾,因为它是一个叶节点)? 因为return(4 = 0 + 0)将为false并且整个循环将变为false?

int isLeaf(struct node *node)
{
  if(node == NULL)
    return 0;
  if(node->left == NULL && node->right == NULL)
    return 1;
    return 0;
}

int isSumTree(struct node* node)
{
  int ls; // for sum of nodes in left subtree
  int rs; // for sum of nodes in right subtree

  /* If node is NULL or it's a leaf node then
   return true */
   if(node == NULL || isLeaf(node))
    return 1;

   if( isSumTree(node->left) && isSumTree(node->right))
   {
     // Get the sum of nodes in left subtree
     if(node->left == NULL)
        ls = 0;
     else if(isLeaf(node->left))
        ls = node->left->data;
     else
        ls = 2*(node->left->data);

     // Get the sum of nodes in right subtree
     if(node->right == NULL)
        rs = 0;
     else if(isLeaf(node->right))
        rs = node->right->data;
     else
        rs = 2*(node->right->data);

     /* If root's data is equal to sum of nodes in left
       and right subtrees then return 1 else return 0*/
     return(node->data == ls + rs);
  }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

我假设你指的是行

if(node->left == NULL)
    ls = 0;

if(node->right == NULL)
    rs = 0;

当左右孩子不存在时,该解决方案的作者初始化 rs并且ls为0。需要此初始化,因为之前没有对ls和rs的赋值。如果你没有这个步骤,你的ls和rs可能是垃圾值。

您可以在声明时初始化ls和rs值来保存上述检查。

int ls = 0,rs = 0;

希望这有帮助!

相关问题