简体   繁体   English

是否可以在小于O(n log n)的时间内比较两个二叉树?

[英]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.

相关问题 是否可以使嵌套的for循环小于O(N ^ 2)? - Is it possible to make this nested for loop less than O(N^2)? 有没有办法在少于 O(n) 的时间内连接 Java 字符串? - Is there a way to concatenate Java strings in less than O(n) time? 关于时间复杂度 O(1), O(n), O(log n), O(n log n) 的问题 - Questions about Time complexity O(1), O(n), O(log n), O(n log n) O(n log n)时间复杂度算法? - O(n log n) Time Complexity Algorithm? 为什么具有 O(n) 时间复杂度的 leetcode 提交需要比 O(n log n) 时间复杂度更多的时间来运行? - Why does leetcode submission with O(n) Time Complexity takes more time to run than O(n log n) Time Complexity? 使用Java8单线在少于O(n ^ 2)的时间内找到两个列表中的第一个匹配字符串 - Find first matching string in two lists in less than O(n^2) time using a Java8 one-liner 为什么这个 function 检查二叉树平衡的时间复杂度是 O(n log n)? - Why is the time complexity of this function to check the balance of a Binary Tree O(n log n)? 以 O(log n) 获取二叉树的大小 - Get size of a binary tree in O(log n) 是否可以在n元树中插入,删除和进行类似操作的时间比O(n)短? - Is it possible to achieve a shorter time than O (n) to insert, delete and similar operations in a n-ary tree? 在 O(n * log n) 时间内找到 Array 中加起来等于目标数的两个元素 - Find Two elements in the Array that add up to the Target number in O(n * log n) Time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM