#10402. szjy_6_树_022

szjy_6_树_022

szjy_6_树_022

规定根结点深度为 0。阅读代码,程序输出是( )。

#include <iostream>
using namespace std;

struct Node {
int value;
Node* left = nullptr;
Node* right = nullptr;
};

int sumDepth(Node* root, int d) {
if (root == nullptr) return 0;
return d + sumDepth(root->left, d + 1)
+ sumDepth(root->right, d + 1);
}

int main() {
Node a{1}, b{2}, c{3}, d{4}, e{5};
a.left = &b;  a.right = &c;
b.left = &d;
c.right = &e;
cout << sumDepth(&a, 0);
}

{{ select(1) }}

  • 5
  • 6
  • 7
  • 8