题目:如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。
只有给定的树是单值二叉树时,才返回 true;否则返回 false。
class Solution {
public boolean isUnivalTree(TreeNode root)
{
if(root==null||(root.right==null&&root.left==null))
return true;
help(root);
if(set.size()==1)
return true;
return false;
}
Set<Integer> set = new HashSet();//哈希集合去重复
public void help(TreeNode root)//遍历二叉树,将值加入set集合
{
if(root==null)
return ;
set.add(root.val);
help(root.left);
help(root.right);
}
}
利用哈希set无重复值的特性,对二叉树进行遍历,判断最终哈希set中元素的个数,大于一则不是单值二叉树,考虑边界情况,树为空和仅有一个节点,均直接返回true;