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 | 476 Views, 19716 Search Bots | 135 Words
| Browse | Archive
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Category: Computing | 476 Views, 19716 Search Bots | 135 Words
| 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:
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:
Tags: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | English | Home Page | Cateogry: Computing | 476 Views, 19716 Search Bots | 135 Words 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
Related Articles
- How to Play WAV music under DOS?
- CPU Utilization
- Design Tic-Tac-Toe
- Sort a Partially Sorted List
- Daily Interview Problem: Maximum Profit From Stocks
- Algorithm Interview: Lowest Common Ancestor of 2 Nodes in Binary Tree
- ImageMagick Vulnerabilities - CVE-2016–3714
- Algorithm Interview: Subarray With Target Sum
- Daily Interview Problem: Merge K Sorted Linked Lists
- [Daily Problem] Add two numbers as a linked list
©2006~2024 SteakOverCooked - 0.013 Seconds(s) - 1480.171 KB/s - 37 Online Memory: 494.06 KB
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - Server PHP Version: 7.4.33
How to Cook a Perfect Steak? | <meta name="robots" content="noindex, follow" />
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - Server PHP Version: 7.4.33
Comments (0)
Read & Write - Normal - Mini - Post - All Comments - Statistics
Be the first one to comment this page !