【问题标题】:Check if a binary tree is a sum tree检查二叉树是否是和树
【发布时间】:2015-04-23 21:43:20
【问题描述】:

方法:

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

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

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

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

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;
}

【问题讨论】:

    标签: binary-tree


    【解决方案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;
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      相关资源
      最近更新 更多