作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在寻找很多面试问题,其中的问题需要同时遍历两棵树,但我不确定具体如何去做。
例如
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/
我想构建 2 个树结构。第一个树将包含节点,每个节点都有我的 Range 对象的列表: class Range { public DateTime Start { get; set; }
我是一名优秀的程序员,十分优秀!