页面顶部 Top
文件:  root - text - article - 2019 - 12 - full-binary-tree.txt
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 436 次阅读, 14355 次搜索 | 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, | 英文 | 主页 | 类别: 计算机科学 | 436 次阅读, 14355 次搜索 | 171 个单词 定阅此目录的博客

猜您喜欢...

  1. [Daily Problem] Validate Balanced Parentheses
  2. Generate All IP Addresses
  3. Top K Frequent words
  4. Daily Interview Problem: Look and Say Sequence
  5. Daily Interview Problem: Queue Using Two Stacks
  6. Daily Interview Problem: Running Median
  7. Daily Interview Problem: Merge K Sorted Linked Lists
  8. Plus One
  9. Daily Interview Puzzle: Minimum Size Subarray Sum
  10. Daily Interview Question: Longest Sequence with Two Unique Numbers

评论 (0)

    当前页暂时没有评论。


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