如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。
只有给定的树是单值二叉树时,才返回 true;否则返回 false。
示例 1:
输入:[1,1,1,1,1,null,1]
输出:true
示例 2:
输入:[2,2,2,5,2]
输出:false
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/univalued-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
递归判断单值
/**
* 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 {
public boolean isUnivalTree(TreeNode root) {
int value = root.val;
return isUnitValue(root,value);
}
public boolean isUnitValue(TreeNode root,int value){
if(root==null)return true;
if(root.val != value)return false;
return isUnitValue(root.left,value)&&isUnitValue(root.right,value);
}
}
递归判断节点值
/**
- 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 {
public boolean isUnivalTree(TreeNode root) {
if(root==null) return true;
//判断子节点是否跟根节点是否一致
if(root.left!=null&&root.left.val!=root.val) return false;
if(root.right!=null&&root.right.val!=root.val) return false;
return isUnivalTree(root.left)&&isUnivalTree(root.right);
}
}