leetcode-501. 二叉搜索树中的众数

leetcode

题目

501. 二叉搜索树中的众数

解法

主要是考的一个特性: 二叉搜索树的中序遍历结果是递增的数列
然后就相当于是对一个递增数列求众数的逻辑了

class Solution {
    private $maxCount = 0;
    private $base = null;
    private $curCount = 0;
    private $ret = [];

    /**
     * @param TreeNode $root
     * @return Integer[]
     */
    function findMode($root) {
        $this->mid($root);
        return $this->ret;
    }

    public function mid(TreeNode $root) {
        if (empty($root)) {
            return;
        }

        if (!empty($root->left)) {
            $this->mid($root->left);
        }

		// 先判断当前值的数量
        if (!is_null($this->base) && $root->val == $this->base) {
            $this->curCount++;
        } else {
            $this->curCount = 1;
        }

		// 当前值数量大于最大数, 覆盖返回值
        if ($this->curCount > $this->maxCount) {
            $this->ret = [$root->val];
            $this->maxCount = $this->curCount;
        } elseif ($this->curCount == $this->maxCount) {
            $this->ret[] = $root->val;
        }

        $this->base = $root->val;

        if (!empty($root->right)) {
            $this->mid($root->right);
        }

    }
}

参考

posted @ 2022-01-02 22:42  吴丹阳-V  阅读(23)  评论(0编辑  收藏  举报