[LeetCode]#965. Univalued Binary Tree

Fatboy Slim
Jan 22, 2021

--

Environment: Python 3.8

Key technique: TreeNode

A binary tree is univalued if every node in the tree has the same value.

Return true if and only if the given tree is univalued.

Example 1:

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

Example 2:

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

Analysis:

  1. val=2, val.left=2, val.right=2. (True)
  2. val=2, val.left=5, val.right=2 (False)
  3. val=2, val.left=2, val.right=null (True)
  4. Return False

Solution:

class Solution:
def isUnivalTree(self, root):
if not root:
return True

if root.left:
if root.val != root.left.val:
return False

if root.right:
if root.val != root.right.val:
return False
left_b = self.isUnivalTree(root.left)
right_b = self.isUnivalTree(root.right)
ans=left_b and right_b

return ans

Submissions:

Reference:

https://leetcode.com/problems/univalued-binary-tree/discuss/1012405/python-recursive-DFS-short-and-easy-understanding-Ivy

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet