码迷,mamicode.com
首页 > 其他好文 > 详细

Interview-Largest independent set in binary tree.

时间:2014-12-24 08:40:08      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

BT(binary tree), want to find the LIS(largest independent set) of the BT. LIS: if the current node is in the set, then its children should not be in the set. So that the set has the largest number of nodes.

Analysis:

Recursion method. Return the LIS of current root. Argument include whether the father of current root is in the LIS.

1. Father of root is not in LIS, then we have two choice:

  1.1 current root in LIS, then we recursively get LIS(root, father not in) =  LIS(root.left, root in LIS) + LIS(root.right, root in LIS) + 1.

  1.2. current root not in LIS, then we recursively get LIS(root,father not in) = LIS(root.left, root not in) +LIS(root.right, root not in).

  we then return the larger one.

2. Father of root is in LIS, then we only have on choice:

  current root not in LIS, then we recursively get LIS(root,father not in) = LIS(root.left, root not in) +LIS(root.right, root not in).

NOTE: we notice that this recursive method has a lot of repeated calculation. we can use memorized search.

Return: {LIS(root in), LIS(root not in)}.

For each current root, we calculate {LIS{root.left in), LIS(root.left not in)} and {LIS{root.right in), LIS(root.right not in)}

Then we have LIS(root in) = Lis(root.left not in)+Lis(root.right not in)+1.

LIS(root not in) = max{LIS{root.left in), LIS(root.left not in)} + max{LIS{root.right in), LIS(root.right not in)}

Interview-Largest independent set in binary tree.

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4181536.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!