# 60. 计算三叉搜索树的高度

60 60-1

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

const tree = new Tree();
let root = null;
rl.on('line', function(line) {
    rl.on('line', (nums) => {
        nums.split(' ').forEach(num => {
            root = tree.insert(root, parseInt(num));
        });
        const height = tree.getHeight(root);
        console.log(height);
    })
});

class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.mid = null;
        this.right = null;
    }
}

class Tree {
    insert(root, val) {
        if (root === null) {
            return new TreeNode(val);
        }
        if (val < root.val - 500) {
            root.left = this.insert(root.left, val);
        } else if (val > root.val + 500) {
            root.right = this.insert(root.right, val);
        } else {
            root.mid = this.insert(root.mid, val);
        }
        return root;
    }

    getHeight(root) {
        if (root === null) {
            return 0;
        }
        let leftHeight = this.getHeight(root.left);
        let rightHeight = this.getHeight(root.right);
        let midHeight = this.getHeight(root.mid);
        return Math.max(leftHeight, midHeight, rightHeight) + 1;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52