开幕式烟火
题目:
这道题一看就是关于树的遍历,对应树和图我们首先的想法就是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执行结果: