965. Univalued Binary Tree ¶ Time: $O(n)$ Space: $O(h)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12class Solution { public: bool isUnivalTree(TreeNode* root) { if (root == nullptr) return true; if (root->left != nullptr && root->left->val != root->val) return false; if (root->right != nullptr && root->right->val != root->val) return false; return isUnivalTree(root->left) && isUnivalTree(root->right); } }; 1 2 3 4 5 6 7 8 9 10 11class Solution { public boolean isUnivalTree(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 isUnivalTree(root.left) && isUnivalTree(root.right); } } 1 2 3 4 5 6 7 8 9class Solution: def isUnivalTree(self, root: TreeNode | None) -> bool: if not root: return True if root.left and root.left.val != root.val: return False if root.right and root.right.val != root.val: return False return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)