文件: root - text - article - 2019 - 12 - full-binary-tree.txt
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 738 次阅读, 19656 次搜索 | 171 个单词
| 浏览 | 博客存档
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 738 次阅读, 19656 次搜索 | 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:
标签: 每日算法题, 算法, 数据结构, 面试题, Daily Interview Problem, Data Structures and Algorithms, Computer Programming, Python, | 英文 | 主页 | 类别: 计算机科学 | 738 次阅读, 19656 次搜索 | 171 个单词 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
猜您喜欢...
- Invert a Binary Tree
- Daily Interview Problem: First Missing Positive Integer
- Daily Interview Problem: Product of Array Except Self
- YES!!
- Algorithm Interview: Determine If Linked List is Palindrome
- Print a tree level-by-level, with line-breaks
- CPU Utilization
- [Daily Problem] Longest Palindromic Substring
- Fibonacci coding
- Find Pythagorean Triplets
©2006~2024 牛排过熟 - 0.00706 秒 - 7793.276 KB/s - 34 在线 内存: 517.64 KB
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - 服务器 PHP 版本号: 7.4.33
牛排怎么做才好吃? | <meta name="机器人" content="不索引, 跟踪" />
18:54:01 up 13 days, 18:33, 2 users, load average: 0.98, 0.86, 0.73 - 服务器 PHP 版本号: 7.4.33
评论 (0)
读写完全 - 一般 - 最小 - 表格 - 所有评论 - 统计
当前页暂时没有评论。