#10430. szjy_6_树_050

szjy_6_树_050

szjy_6_树_050

给定的树是一棵二叉搜索树,根结点深度为 0。阅读代码,程序输出是( )。

#include <iostream>
using namespace std;

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

int findDepth(Node* root, int x, int d) {
if (root == nullptr) return -1;
if (root->value == x) return d;
if (x < root->value) return findDepth(root->left, x, d + 1);
return findDepth(root->right, x, d + 1);
}

int main() {
Node a{40}, b{20}, c{60}, d{10}, e{30}, f{50}, g{70}, h{65};
a.left = &b;  a.right = &c;
b.left = &d;  b.right = &e;
c.left = &f;  c.right = &g;
g.left = &h;
cout << findDepth(&a, 65, 0);
}

{{ select(1) }}

  • 2
  • 3
  • 4
  • -1