leetcode-501. 二叉搜索树中的众数
leetcode
题目
解法
主要是考的一个特性: 二叉搜索树的中序遍历结果是递增的数列
然后就相当于是对一个递增数列求众数的逻辑了
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);
        }
    }
}
参考
本文来自博客园,作者:吴丹阳-V,转载请注明原文链接:https://www.cnblogs.com/wudanyang/p/15758598.html

                
            
        
浙公网安备 33010602011771号