[英]Is it possible to compare two binary trees in less than O(n log n) time?
I wrote a java routine to compare 2 binary trees. 我编写了一个java例程来比较2个二叉树。 I am looking for better algorithms that run in less time.
我正在寻找在更短的时间内运行的更好的算法。
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if ( p == null && q==null)
return true;
if (p == null || q == null)
return false;
if ( (p.val == q.val) && isSameTree(p.left, q.left) &&
isSameTree(p.right, q.right))
return true;
else
return false;
}
}
My code takes O(n log n) time. 我的代码需要O(n log n)时间。
How to approach reducing the time required? 如何减少所需的时间?
The current runtime of your approach is actually O(n)
, where n
should be the number of nodes of the tree with lesser(or if they're equal) nodes . 您的方法的当前运行时实际上是
O(n)
,其中n
应该是具有较小(或如果它们相等)节点的树的节点数 。
Also, note to compare all the values of a data structure you would have to visit all of them and that is the runtime you could achieve and not reduce further. 另外,请注意比较数据结构的所有值, 您必须访问所有这些值 ,这是您可以实现的运行时间而不是进一步减少。 In the current case, at the worst, you would have to visit all the nodes of the smaller tree and hence
O(n)
. 在当前情况下,最坏的情况是,您必须访问较小树的所有节点,因此必须访问
O(n)
。
Hence any other approach though might help you with conditional optimization, your current solution has an optimal runtime which cannot be reduced further. 因此,任何其他方法都可以帮助您进行条件优化,您当前的解决方案具有无法进一步降低的最佳运行时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.