1. 问题
A binary tree is univalued if every node in the tree has the same value.
Return true if and only if the given tree is univalued.
如果一棵二叉树中的每个节点的值都相等,则该二叉树是唯一树,返回 true。否则返回 false。
2. 解题思路
如果给定的二叉树是空的,则直接返回 true。否则,取出根节点的值,再对给定的二叉树做一个层序遍历,判断是否每个节点的值都等于根节点的值。
3. 代码示例
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isUnivalTree(TreeNode root) {
if (root == null) {
return true;
}
int val = root.val;
boolean reault = true;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode currentRoot = queue.poll();
if(val != currentRoot.val) {
reault = false;
break;
}
if(currentRoot.left != null) {
queue.offer(currentRoot.left);
}
if(currentRoot.right != null) {
queue.offer(currentRoot.right);
}
}
return reault;
}
}
网友评论