当前位置: 面试刷题>> 二叉树的最大节点 (经典算法题500道)


题目描述补充

题目:给定一棵二叉树,请编写一个函数来找到这棵二叉树中的最大节点值。假设二叉树中的节点值都是整数。

示例

假设我们有以下二叉树:

    1
   / \
  3   2
 / \   \
5   3   9

在这个例子中,二叉树的最大节点值为 9。

PHP 示例代码

<?php

class TreeNode {
    public $val;
    public $left;
    public $right;

    function __construct($val = 0, $left = null, $right = null) {
        $this->val = $val;
        $this->left = $left;
        $this->right = $right;
    }
}

function findMaximumValue($root) {
    if ($root === null) {
        return PHP_INT_MIN; // 返回一个比任何可能节点值都小的数
    }
    
    $leftMax = findMaximumValue($root->left);
    $rightMax = findMaximumValue($root->right);
    
    return max($root->val, $leftMax, $rightMax);
}

// 示例用法
$root = new TreeNode(1);
$root->left = new TreeNode(3);
$root->right = new TreeNode(2);
$root->left->left = new TreeNode(5);
$root->left->right = new TreeNode(3);
$root->right->right = new TreeNode(9);

echo findMaximumValue($root); // 输出 9

?>

Python 示例代码

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def findMaximumValue(root):
    if not root:
        return float('-inf')  # 返回一个比任何可能节点值都小的数
    
    left_max = findMaximumValue(root.left)
    right_max = findMaximumValue(root.right)
    
    return max(root.val, left_max, right_max)

# 示例用法
root = TreeNode(1)
root.left = TreeNode(3)
root.right = TreeNode(2)
root.left.left = TreeNode(5)
root.left.right = TreeNode(3)
root.right.right = TreeNode(9)

print(findMaximumValue(root))  # 输出 9

JavaScript 示例代码

function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

function findMaximumValue(root) {
    if (!root) {
        return -Infinity; // 返回一个比任何可能节点值都小的数
    }
    
    const leftMax = findMaximumValue(root.left);
    const rightMax = findMaximumValue(root.right);
    
    return Math.max(root.val, leftMax, rightMax);
}

// 示例用法
const root = new TreeNode(1);
root.left = new TreeNode(3);
root.right = new TreeNode(2);
root.left.left = new TreeNode(5);
root.left.right = new TreeNode(3);
root.right.right = new TreeNode(9);

console.log(findMaximumValue(root)); // 输出 9

// 码小课网站中有更多相关内容分享给大家学习

以上代码展示了如何在 PHP、Python 和 JavaScript 中实现寻找二叉树最大节点值的算法。

推荐面试题