二叉树最大值查找

源代码:

class TreeNode {
    constructor(value = 0, left = null, right = null) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}

function findMaxValue(root) {
    if (root === null) {
        return -Infinity;
    }
    let leftMax = findMaxValue(root.left);
    let rightMax = findMaxValue(root.right);
    return Math.max(root.value, leftMax, rightMax);
}

const root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(20);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(7);
root.right.right = new TreeNode(15);

// 求树中的最大值
const maxValue = findMaxValue(root);
console.log("树中的最大值是:", maxValue);

运行结果: