页面顶部 Top
文件:  root - text - article - 2019 - 12 - full-binary-tree.txt
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 438 次阅读, 14689 次搜索 | 171 个单词

定阅此目录的博客 | 浏览 | 博客存档
Hi, here's your problem today. This problem was recently asked by Google:

Given a binary tree, remove the nodes in which there is only 1 child, so that the binary tree is a full binary tree.

So leaf nodes with no children should be kept, and nodes with 2 children should be kept as well.

Here's a starting point:


from collections import deque

class Node(object):
def __init__(self, value, left=None, right=None):
self.left = left
self.right = right
self.value = value
def __str__(self):
q = deque()
q.append(self)
result = ''
while len(q):
num = len(q)
while num > 0:
n = q.popleft()
result += str(n.value)
if n.left:
q.append(n.left)
if n.right:
q.append(n.right)
num = num - 1
if len(q):
result += "\n"

return result

def fullBinaryTree(node):
# Fill this in.

# Given this tree:
# 1
# / \
# 2 3
# / / \
# 0 9 4

# We want a tree like:
# 1
# / \
# 0 3
# / \
# 9 4

tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
tree.right.right = Node(4)
tree.right.left = Node(9)
tree.left.left = Node(0)
print fullBinaryTree(tree)
# 1
# 03
# 94
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 438 次阅读, 14689 次搜索 | 171 个单词 定阅此目录的博客

猜您喜欢...

  1. Spreadsheet Column Title
  2. Daily Interview Problem: Decode String
  3. Find Pythagorean Triplets
  4. Daily Interview Problem: Given two arrays, write a function to compute their intersection.
  5. Linode Support Ticket 10029540 - Other - Important Notice Regarding Ubuntu 17.10 Image
  6. Daily Interview Question: Create a Simple Calculator
  7. Algorithm Interview: Shifted String
  8. Daily Interview Problem: Merge List Of Number Into Ranges
  9. Algorithm Interview Question: Nth Fibonacci Number
  10. Daily Interview Problem: Group Words that are Anagrams

评论 (0)

    当前页暂时没有评论。


最后更新: October 30 2020 14:21:12 | RSS Subscription
牛排怎么做才好吃? | <meta name="机器人" content="不索引, 跟踪" />