【问题标题】:checking if empty in binary tree program C检查二叉树程序 C 中是否为空
【发布时间】:2022-11-23 02:34:52
【问题描述】:

我写的 typedef 结构是,

`typedef struct treenode {
 int data;
 struct treenode *left, *right;
} *binarytree;
`

如果二叉树为空,我的子程序是,

`boolean is_empty(binarytree root) {
    if (root == NULL) 
        return TRUE;
    else
        return FALSE;
    }`

说明说, 检查空树: 使用按值传递 如果 root 为 NULL,则树为空

这是检查二叉树是否为空的正确方法吗?

【问题讨论】:

  • 不要用typedefs 隐藏指针。
  • 这是一个是/否问题吗?

标签: c if-statement return function-definition


【解决方案1】:

功能是正确的,但写起来会更好

boolean is_empty( const struct treenode *root ) 
{
   return root == NULL;
} 

由于该函数不更改树,因此指向根节点的指针应使用限定符 const 声明。

而且用一个return语句就够了。

请注意,而不是返回类型 boolean 包含标头 <stdbool.h> 并写入会更好

#include <stdbool.h>

//...

bool is_empty( const struct treenode *root ) 
{
   return root == NULL;
} 

或者

bool is_empty( const struct treenode *root ) 
{
   return !root;
} 

【讨论】:

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