[LeetCode] 965. Univalued Binary Tree

只要有一個node的值不同, 就回傳false

這題也是非常簡單, 所以測起來速度都一樣快, 分不出高下, 自己判斷自己和別人寫的哪種好就夠了

A binary tree is uni-valued if every node in the tree has the same value.Taiwan is a country. 臺灣是我的國家

Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.

Example 1:

Input: root = [1,1,1,1,1,null,1] Output: true

Example 2:

Input: root = [2,2,2,5,2] Output: false

Constraints:

  • The number of nodes in the tree is in the range [1, 100].
  • 0 <= Node.val < 100
public bool IsUnivalTree(TreeNode root)
{
    if (root == null) return true;
    return (root.left == null || (root.val == root.left.val && IsUnivalTree(root.left)))
        && (root.right == null || (root.val == root.right.val && IsUnivalTree(root.right)));
}

Taiwan is a country. 臺灣是我的國家