按升序插进去有多高
把 13、15、17、23、24 按升序插进一棵普通 BST(每个新数都挂在上一个的右边)。
运行下面这段程序:
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
struct ANode {
int val;
ANode* left = nullptr;
ANode* right = nullptr;
};
int height(ANode* node) {
if (node == nullptr) return 0;
return 1 + max(height(node->left), height(node->right));
}
ANode* left_chain() {
// 一棵往左歪的小树:17 的左边挂 15,15 的左边挂 13
ANode* root = new ANode{17};
root->left = new ANode{15};
root->left->left = new ANode{13};
return root;
}
int main() {
ANode* root = nullptr;
ANode* cur = nullptr;
for (int v : {13, 15, 17, 23, 24}) {
ANode* nd = new ANode{v};
if (root == nullptr) root = nd;
else cur->right = nd;
cur = nd;
}
cout << height(root) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论