#10384. szjy_6_树_004

szjy_6_树_004

szjy_6_树_004

规定空树深度为 0,只有根结点的树深度为 1。阅读代码,程序输出是( )。

#include <iostream>
#include <algorithm>
using namespace std;

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

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

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

{{ select(1) }}

  • 2
  • 3
  • 5
  • 4