LeetCode简单题分享(14)

开幕式烟火

题目:

         这道题一看就是关于树的遍历,对应树和图我们首先的想法就是DFS和BFS的选择

        不清楚DFS和BFS的可以看看这个:

BFS,DFS,以及图(Graph),树(Tree)的思考(6)_PigeonEssence的博客-CSDN博客

        通过提示我们可以看到,节点个数是小于1000个的,数字也小于1000

        那么我们就不用考虑到dfs的栈溢出问题,就用最简单的递归来求解了。这道题返回的是颜色种类,那么很容易就可以想到用hashSet去重实现。

代码如下:

import java.util.HashSet;
import java.util.Set;

public class dw {
    public static void main(String[] args) {
        Set<Integer> colorSet = new HashSet<>();
        TreeNode tn1 =new TreeNode(1);
        TreeNode tn2 =new TreeNode(3);
        TreeNode tn3 =new TreeNode(2);
        TreeNode tn4 =new TreeNode(1);
        TreeNode tn5 =new TreeNode(2);

        tn1.left=tn2;
        tn1.right=tn3;
        tn2.left=tn4;
        tn4.left=tn5;

        TreeNode root =tn1;
        System.out.println(numColor(root,colorSet));
    }

    /*
    * 调用dfs递归方法,返回最终结果
    * */
    public static int numColor(TreeNode root, Set<Integer> colorSet) {
        dfs(root,colorSet);
        return colorSet.size();
    };
    /*
    * 递归函数调用dfs遍历tree
    * */
    public static void dfs(TreeNode root, Set<Integer> colorSet)
    {
        if (root != null)
        {
            /*colorSet就是一个hashset,智慧存储相同的东西,用于去重*/
            colorSet.add(root.val);
            /*先左在右,深度优先*/
            dfs(root.left,colorSet);
            dfs(root.right,colorSet);
        }
    }
}

leetcode执行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PigeonEssence

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值