LC.P965[单值二叉树]

方法一:DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 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 {

int val = -1;

public boolean isUnivalTree(TreeNode root) {
if (val == -1) val = root.val;
if (root == null) return true;
if (root.val != val) return false;
return isUnivalTree(root.left) && isUnivalTree(root.right);
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$