Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

How to approach reducing the time required?

like image 376
Louise Avatar asked Jan 07 '19 00:01

Louise


People also ask

Why is the time complexity of binary search O log n?

The time complexity of the binary search algorithm is O(log n). The best-case time complexity would be O(1) when the central index would directly match the desired value. Binary search worst case differs from that. The worst-case scenario could be the values at either extremity of the list or values not in the list.

What is the time complexity of a binary tree?

In any binary search tree the time complexity taken is O(h), where h is the height of the tree.. Since it is given that tree is balanced binary search tree so searching for an element in worst case is O(logn).

How will you check if 2 binary trees are equal or not?

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Constraints: The number of nodes in both trees is in the range [0, 100] .


1 Answers

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.

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).

Hence any other approach though might help you with conditional optimization, your current solution has an optimal runtime which cannot be reduced further.

like image 172
Naman Avatar answered Nov 15 '22 19:11

Naman