c - 二叉树镜像()这是如何工作的?

标签 c data-structures

虽然它看起来非常简单明了,但我在理解这段代码的核心方面确实遇到了一些困难。给定一个简单的二叉树,这个著名的函数会生成同一棵树的镜像结果。

void mirror(struct node* node) {
  if (node==NULL) {
    return;
  }
  else {
    struct node* temp;

    // do the subtrees
    mirror(node->left); //this part confuses me
    mirror(node->right); //so does this 

    // swap the pointers in this node
    temp = node->left;
    node->left = node->right;
    node->right = temp;
  }
}

这就是代码。阅读这段代码后,我有两个问题。

  1. mirror(node->left) 和 mirror(node->right) 在调用栈上放置两个连续的函数调用。我的理解是,首先, 函数在左节点上调用,然后在右节点上调用。这个流程 只要节点为空,就会重复出现。但是当它不为空时 它返回?它是否只是返回调用语句而没有 返回任何东西?

  2. 如何从调用堆栈调用这些函数?这将是 如果有人运行函数调用并告诉 我们如何以及为什么需要两次连续的函数调用。

附言:为什么不在此范围内使用迭代?

EDIT: quoting a useful comment by EOF, is it possible to tail-recurse this function by moving the swapping before the two recursive calls?

最佳答案

  1. mirror(node->left) and mirror(node->right) places two consecutive function calls on the call stack.

这是一种奇怪的表达方式,它可能反射(reflect)出一种误解。从来没有一次调用堆栈包含这些函数调用的表示。两者

My understanding is, first, the function is called on the left node and then right. This process recurs as long as node is empty. But when it is not empty what does it return?

该函数的类型为 void。它从不返回任何东西。

Does it just come back to the call statement without returning anything?

是的,当函数完成时,控制会继续执行函数调用后的下一条语句。

  1. How are these functions invoked from the call stack?

函数不是从调用堆栈“调用”的。堆栈帧是为函数创建的,并作为调用函数过程的一部分进行推送。详细信息未指定;编译器负责生成代码以执行正确的操作。

It would be really helpful if someone runs through the function calls and tells how and why do we need two consecutive function calls.

镜像整棵树意味着反转每个节点的子节点。因此,在处理给定节点时,函数必须确保该节点的子节点都被镜像。它通过对每个执行递归调用然后交换它们来实现这一点。

关于c - 二叉树镜像()这是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29925857/

相关文章:

data-structures - 如果您知道二叉树的节点数,如何找到二叉树的最小高度?

javascript - 在 JS 中旋转和转换数据

c - 如何删除 ':' token 之前的错误 : expected ',' , ';' 、 '}' 、 '__attribute__' 或 '=' ?

c - 为什么这个简单的代码没有出现段错误?

c - 有没有办法在 Linux 中使用 C 以编程方式设置接口(interface) MTU?

CYGWIN Ms-Dos 路径检测到警告

c - 如何访问 C 中结构中索引处的元素?

objective-c - Objective C bool 属性和内存

c++ - cvSetImageData 和 cvCreateImage c++ 等效接口(interface)

java - ConcurrentHashMap 的 concurrencyLevel 参数给我们什么保证?