gpt4 book ai didi

algorithm - 一起遍历两棵树?

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

我正在寻找很多面试问题,其中的问题需要同时遍历两棵树,但我不确定具体如何去做。

例如

Given references to roots of two binary trees, how do you determine whether the sequence of the leaf elements equal but you must implement short circuiting return when the first node violates the rule.

最佳答案

您的问题是想了解是否:"访问2棵树的所有叶子节点所产生的序列是相同的"

有一个约束,当发现叶值不匹配时,我们必须立即退出。

如果是这样,我提出以下解决方案:

insert (root of tree1) in stack1
insert (root of tree2) in stack2

temp1 = (root of tree1) -> left child
temp2 = (root of tree2) -> left child

while(stack1 and stack2 arent empty)
{
found = false
while(found == false) {
if (temp1 is leaf node)
child1 = value of temp1
found = true
pop element from stack1
set temp1 to its right child

if (temp1 has left child)
put temp1 in stack1
set temp1 to its left child
}

found = false
while(found == false) {
if (temp2 is leaf node)
child2 = value of temp2
found = true
pop element from stack2
set temp2 to its right child

if (temp2 has left child)
put temp2 in stack2
set temp2 to its left child
}

if(child1 != child2)
return
}

关于algorithm - 一起遍历两棵树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9389065/

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