gpt4 book ai didi

java - 计算树上的匹配节点

转载 作者:行者123 更新时间:2023-12-02 08:54:16 25 4
gpt4 key购买 nike

我正在尝试这个problem在 Practice-It 上,但已经有一段时间遇到麻烦了。

Write a method matches that returns a count of the number of nodes in one tree that match nodes in another tree. A match is defined as a pair of nodes that are in the same position in the two trees relative to their overall root and that store the same data.

到目前为止,我已经尝试了以下操作,但我不太清楚我想要的计数,而且我不太清楚为什么。

public int matches(IntTree t2)
{
return match(overallRoot, t2.overallRoot);
}

public int match(IntTreeNode tree1, IntTreeNode tree2)
{
if(tree1 == null && tree2 == null)
return 1;
if(tree1 == null || tree2 == null)
return 0;
if(tree1.data == tree2.data)
return 1;
int left = match(tree1.left, tree2.left);
int right = match(tree1.right, tree2.right);
return left + right;
}

任何帮助将不胜感激!

最佳答案

如果当前节点匹配,您将停止搜索。如果不同,则检查左右,但在匹配时返回一个。

关于java - 计算树上的匹配节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60588167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com