gpt4 book ai didi

algorithm - "cracking the coding interview(fourth edition)": 4. 7 子树检查

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:32:28 25 4
gpt4 key购买 nike

You have two very large trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1

作者给出了一个暴力搜索的解决方案,做一下对比一个节点一个节点。以下是代码:

boolean containsTree(TreeNode t1, TreeNode t2) {
if (t2 == null) return true;
else return subTree(t1, t2);
}

boolean subTree(TreeNode r1, TreeNode r2) {
if(r1 == null)
return false;
if(r1.data = r2.data){
if(matchTreee(r1, r2)) return true;
}
return ( subTree(r1.left, r2) || subTree(r1.right, r2) );
}

boolean matchTree(TreeNode r1, TreeNode r2){
if (r2 == null && r1 == null)
return true;
if (r1 == null || r2 == null)
return false; //big tree empty & subtree still not found
if (r1.data != r2.data)
return false;
return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right));
}

在上面的代码中,我不同意函数 matchTree 的基本情况

if (r2 == null && r1 == null)
return true;
if (r1 == null || r2 == null)
return false; // big tree empty & subtree still not found

根据我的理解,基本情况应该是:

    if(r2 == null) return true; //if r2 is null, r2 must match r1 
no matter r1 is null or not
if(r1 == null) return false; //r1 == null means big tree empty
and we already know r2 != null, so r2 must not match r1.

大家可以帮我验证一下吗?

谢谢,

最佳答案

在我看来,这本书的作者对 T2 is a subtree of T1 的定义与您的不同。

例如,考虑下面的树(疯狂的 Paint 技能):

Trees

作者的代码认为 T3 是 T1 的子树,而不是 T2。你认为 T2 和 T3 都是 T1 的子树。

也就是说,我认为您的基本案例对于“子树”的“自然”定义更有意义。

C# 测试代码(带有int 类型的data):

var t1 = new TreeNode() { data = 0,
left = new TreeNode() { data = 1,
left = new TreeNode() { data = 2 },
right = new TreeNode() { data = 3,
right = new TreeNode() { data = 4 } } } };

var t2 = new TreeNode() { data = 1,
left = new TreeNode() { data = 2 },
right = new TreeNode() { data = 3 } };

var t3 = new TreeNode() { data = 1,
left = new TreeNode() { data = 2 },
right = new TreeNode() { data = 3,
right = new TreeNode() { data = 4 } } };

关于algorithm - "cracking the coding interview(fourth edition)": 4. 7 子树检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12534842/

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