Redian新闻
>
Find a sub tree with min weight怎么做
avatar
Find a sub tree with min weight怎么做# JobHunting - 待字闺中
S*C
1
the weight of a tree = sum of weight of all node in the tree. Weight of node
= value of node * level of the node in the tree。
这里的代码能计算weight
public int findWeight(TreeNode root) {
int res = 0;
if (root == null)
return res;
List curLevel = new ArrayList();
curLevel.add(root);
int level = 1;
while (!curLevel.isEmpty()) {
for (TreeNode p : curLevel)
res += p.val * level;
level ++;
List parentLevel = curLevel;
curLevel = new ArrayList();
for (TreeNode p : parentLevel) {
if (p.left != null)
curLevel.add(p.left);
if (p.right != null)
curLevel.add(p.right);
}
}
return res;
}
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。