代码随想录——二叉搜索树中的众数(Leetcode501)

题目链接
在这里插入图片描述

中序遍历

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int max = 0;
    int count = 0;
    TreeNode pre = null;
    ArrayList<Integer> array = new ArrayList<Integer>();
    public int[] findMode(TreeNode root) {
        traversal(root);
        // 把ArrayList转为int[]
        int[] result = new int[array.size()];
        for (int i = 0; i < array.size(); i++) {
            result[i] = array.get(i);
        }
        return result;
    }
    // 中序遍历
    public void traversal(TreeNode root){
        if(root == null){
            return ;
        }
        // 左
        traversal(root.left);
        // 中
        if(pre == null){
            count = 1;
        }else if(pre.val == root.val){
            count++;
        }else{
            count = 1;
        }
        pre = root;

        if(count == max){
            array.add(root.val);
        }

        if(count > max){
            max = count;
            // ArrayList中清空数组函数clear()
            array.clear();
            array.add(root.val);
        }
        // 右
        traversal(root.right);
    }
}

由于二叉搜索树中序遍历是升序的特性,所以当看到题目中是二叉搜索树时,首先可以想用中序遍历来解决。

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值