965. Univalued Binary Tree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean isUnivalTree(TreeNode root) {
return dfs(root);
}

private boolean dfs(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 dfs(root.left) && dfs(root.right);
}
}

References

965. Univalued Binary Tree