Skip to content

Commit c099d43

Browse files
authored
Create 965. Univalued Binary Tree
1 parent c8b6cf8 commit c099d43

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

965. Univalued Binary Tree

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
// A binary tree is univalued if every node in the tree has the same value.
3+
// Return true if and only if the given tree is univalued.
4+
5+
Example 1:
6+
Input: [1,1,1,1,1,null,1]
7+
Output: true
8+
9+
Example 2:
10+
Input: [2,2,2,5,2]
11+
Output: false
12+
*/
13+
14+
/**
15+
* Definition for a binary tree node.
16+
* public class TreeNode {
17+
* int val;
18+
* TreeNode left;
19+
* TreeNode right;
20+
* TreeNode(int x) { val = x; }
21+
* }
22+
*/
23+
class Solution {
24+
public boolean isUnivalTree(TreeNode root) {
25+
boolean left_correct = (root.left == null ||
26+
(root.val == root.left.val && isUnivalTree(root.left)));
27+
28+
boolean right_correct = (root.right == null ||
29+
(root.val == root.right.val && isUnivalTree(root.right)));
30+
31+
return left_correct && right_correct;
32+
}
33+
}

0 commit comments

Comments
 (0)