当前位置: 面试刷题>> 寻找树中最左下节点的值 (经典算法题500道)


题目描述补充

给定一棵二叉树,请编写一个函数来找到并返回树中最左下节点的值。最左下节点是指在所有可能的左子树路径中,深度最深的左节点。如果树为空,则返回某个特定的值(例如,nullNoneundefined 或特定的错误码等,具体取决于编程语言的习惯)。

示例

假设有以下二叉树:

    1
   / \
  2   3
 / \
4   5
   /
  6

最左下节点的值为 6。

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 findLeftmostValue($root) {
    if ($root === null) {
        return null; // 或者返回某个特定的错误码
    }
    
    $result = $root->val;
    $current = $root;
    
    while ($current->left !== null) {
        $result = $current->left->val;
        $current = $current->left;
    }
    
    return $result;
}

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

echo findLeftmostValue($root); // 输出 6
?>

Python 示例代码

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

def findLeftmostValue(root):
    if not root:
        return None  # 或者返回某个特定的错误码
    
    result = root.val
    current = root
    
    while current.left:
        result = current.left.val
        current = current.left
    
    return result

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

print(findLeftmostValue(root))  # 输出 6

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 findLeftmostValue(root) {
    if (!root) {
        return null; // 或者返回某个特定的错误码
    }
    
    let result = root.val;
    let current = root;
    
    while (current.left) {
        result = current.left.val;
        current = current.left;
    }
    
    return result;
}

// 示例用法
let root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.left.right.left = new TreeNode(6);

console.log(findLeftmostValue(root)); // 输出 6

码小课网站中有更多相关内容分享给大家学习,涵盖了数据结构、算法等多个方面的深入解析和实战演练,帮助大家更好地掌握编程技能。

推荐面试题