思路:判断每个结点,如果根结点不等于左结点或不等于右结点,则不是单值二叉树。如果左节点或右节点不为空,则继续检查他的左右结点。
/**
* 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.val != root.left.val) {
return false;
}
if(root.right != null && root.val != root.right.val) {
return false;
}
return isUnivalTree(root.left) && isUnivalTree(root.right);
}
}