首页 > 其他 > 详细

面试题54. 二叉搜索树的第k大节点

时间:2020-05-21 11:58:56      阅读:51      评论:0      收藏:0      [点我收藏+]

地址:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/

<?php
/**
面试题54. 二叉搜索树的第k大节点
给定一棵二叉搜索树,请找出其中第k大的节点。



示例 1:

输入: root = [3,1,4,null,2], k = 1
3
/ 1   4
2
输出: 4
示例 2:

输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ 3   6
/ 2   4
/
1
输出: 4
 */
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($value) { $this->val = $value; }
 * }
 */
class Solution {
    private $res = [];
    function kthLargest($root, $k) {
        $this->helper($root);
        return $this->res[$k-1];
    }

    function helper($root){
        if($root==null) return;
        $this->helper($root->right);
        array_push($this->res,$root->val);
        $this->helper($root->left);
    }
}

 

面试题54. 二叉搜索树的第k大节点

原文:https://www.cnblogs.com/8013-cmf/p/12929033.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!