编程题:父子节点不能同时选取,求二叉树中最大子节点和
题干:给定一个二叉树,每个节点具备一个权重值,按照如下规则选取二叉树中的节点,如果选取了某个节点,那么其子节点都不能被选取了。在这个规则下面,求解可能的最大子节点和。
思路:核心思路是递归,求得包含树根节点的最大子节点和以及不包含树根节点的最大子节点和,在根据左右字数的结果处理递归结果。
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def print(self):
node_list = [self]
i = 0
while i < len(node_list):
cur = node_list[i]
print(cur.val)
if cur.left:
node_list.append(cur.left)
if cur.right:
node_list.append(cur.right)
i += 1
print('-'*20)
def load_tree(a):
if not a:
return None
root = TreeNode(a[0])
node_list = [root]
i = 1
j = 0
while i+1 < len(a):
cur = node_list[j]
cur.left = TreeNode(a[i])
cur.right = TreeNode(a[i+1])
node_list.append(cur.left)
node_list.append(cur.right)
i += 2
j += 1
return root
# 题解
def find_largest_subset(node):
if not node:
return 0, 0
rst_with_left, rst_wo_left = find_largest_subset(node.left)
rst_with_right, rst_wo_right = find_largest_subset(node.right)
return node.val + rst_wo_left + rst_wo_right, max(rst_with_left, rst_wo_left) + max(rst_with_right, rst_wo_right)
tree = load_tree([1, 10, 2, 3, 4, 10, 20])
tree.print()
rst = find_largest_subset(tree)
print(rst, max(rst))