c++ - 二叉树递归方法的直径

标签 c++ recursion

我正在尝试使用递归查找直径,我对递归感到困惑

我试过的一些测试用例我在某些时候得到了正确的答案 发生整数溢出,但以下作者的解决方案被接受了相同的数据类型

我的方法:

对于每个节点,经过它的最长路径的长度=它的左子树的最大深度+它的右子树的最大深度。

我的问题是我的实现有什么问题

  class Solution {
  public:
      int mx = 0;
      int solve(TreeNode* root) {
          if (root == NULL)return 0;
          int leftheight = diameterOfBinaryTree(root->left) + 1;
          int rightheight = diameterOfBinaryTree(root->right) + 1;
          mx = max(mx, leftheight + rightheight);
          return max(leftheight, rightheight);
      }
      int diameterOfBinaryTree(TreeNode* root) {
          solve(root);
          return mx;
      }

  };

作者的方法:相同的方法但不同的递归实现

  class Solution {
  public:
      int maxdiadepth = 0;

      int dfs(TreeNode* root) {
          if (root == NULL) return 0;

          int leftdepth = dfs(root->left);
          int rightdepth = dfs(root->right);

          if (leftdepth + rightdepth > maxdiadepth) maxdiadepth = leftdepth + rightdepth;
          return max(leftdepth + 1, rightdepth + 1);
      }

      int diameterOfBinaryTree(TreeNode* root) {
          dfs(root);

          return maxdiadepth;
      }
  };

最佳答案

在工作实现中,递归 dfs 调用返回子树的最大深度。

在您的实现中,递归 diameterOfBinaryTree 调用返回当前累积的直径近似值。您将它分配给名为 leftheightrightheight 的变量 - 这是误导;该值实际上不是左子树或右子树的高度。

关于c++ - 二叉树递归方法的直径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56889392/

相关文章:

c++ - 递归函数抛出非空函数结束警告

python - 为什么这个抛出错误的递归 Python 函数在最后几次调用中来回跳转?

javascript - 如何停止setTimeout递归

c++ - C++中具有相同名称但成员不同的结构

c++ - 为什么编译器将类函数作为非静态函数处理?

c++ - 关于在任何计算机上以相同速度运行程序的问题

c++ - 为什么 autotools 在一台机器上创建 project-File.o,在另一台机器上创建 File.o?

c++ - 为什么将 X 而不是 X<T> 用于模板化构造函数和析构函数?

c++ - 使用 cmd.exe 显示或捕获完整的程序输出

c++递归数组解释