(Daily Coding Problem: February 23rd, 2020)Given the root of a binary tree, count the number of unival subtrees.

Image by https://www.shadabahmed.com/
  1. When the node is null, the answer, in that case, is the no of unival tree is 0.
    But at the same time, it will not affect the parent node’s ability to be a unival tree. Hence, I marked isUnival as true(exception — even though it's not a unival tree, I marked it as true because we are maintaining this only for computing parent node’s isUnival tree feature) and count as 0.
  2. When the node’s left and right nodes are null, in that case, is the no of unival tree is 1.
    Hence, I marked isUnival as true and count as 1.
Node.value has to be equal to node.left.value (if node.left present) and node.right.value (if node.right.present) along with its child nodes have to pass the criteria of univalTree for the current node to be unival.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Divya Biyani

Divya Biyani

Software Developer by profession, with a passion of sharing knowledge.