先对二叉树进行一次完整遍历,将所有节点存入数组中,最后对数组排序后返回目标值。
<?php
class TreeNode
{
public $val = null;
public $left = null;
public $right = null;
function __construct($val = 0, $left = null, $right = null)
{
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
class Solution
{
public $map = [];
/**
* @param TreeNode $root
* @param Integer $k
* @return Integer
*/
public function kthSmallest(TreeNode $root, int $k): int
{
$this->dfs($root);
sort($this->map);
return $this->map[$k - 1];
}
/**
* @param $root
* @return void
*/
public function dfs($root): void
{
if ($root == null) {
return;
}
$this->map[] = $root->val;
$this->dfs($root->left);
$this->dfs($root->right);
}
}
$root = new TreeNode(3);
$root->left = new TreeNode(1);
$root->left->right = new TreeNode(2);
$root->right = new TreeNode(4);
$solution = new Solution();
var_dump($solution->kthSmallest($root, 1));