To the Top
File:  root - text - article - 2019 - 12 - count-number-of-unival-subtrees.txt.txt
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 162 Views, 14593 Search Bots | 135 Words

Subscribe to Feed Burner | Browse | Archive
Hi, here's your problem today. This problem was recently asked by Microsoft:

A unival tree is a tree where all the nodes have the same value. Given a binary tree, return the number of unival subtrees in the tree.

For example, the following tree should return 5:


0
/ \
1 0
/ \
1 0
/ \
1 1


The 5 trees are:
- The three single '1' leaf nodes. (+3)
- The single '0' leaf node. (+1)
- The [1, 1, 1] tree at the bottom. (+1)

Here's a starting point:


class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None

def count_unival_subtrees(root):
# Fill this in.

a = Node(0)
a.left = Node(1)
a.right = Node(0)
a.right.left = Node(1)
a.right.right = Node(0)
a.right.left.left = Node(1)
a.right.left.right = Node(1)

print count_unival_subtrees(a)
# 5
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Cateogry: Computing | 162 Views, 14593 Search Bots | 135 Words Subscribe to Feed Burner

Related Articles

  1. Generate All IP Addresses
  2. Daily Interview Problem: Merge List Of Number Into Ranges
  3. Daily Interview Problem: Deepest Node in a Binary Tree
  4. Algorithm Interview Question: Find the Single Element in an Array of Duplicates
  5. [Daily Problem] Course Prerequisites
  6. Algorithm Interview: Determine If Linked List is Palindrome
  7. Algorithm Interview Question: Nth Fibonacci Number
  8. Longest Substring Without Repeating Characters
  9. Daily Interview Puzzle: Intersection of Linked Lists
  10. [Daily Problem] Angles of a Clock

Comments (0)

Your Email (Domain Part Not Exposed):

Your Comments:

Privately By Mail Colors More Smileys S x y @

Verification (Click Image 2 Refresh):

    Be the first one to comment this page !


Page Edited: October 30 2020 14:21:09 | RSS Subscription
How to Cook a Perfect Steak? | <meta name="robots" content="noindex, follow" />