Common Nodes in Two Binary Search Trees

Given two BSTs, return the sum of all common nodes in both.
In case there is no common node, return 0

NOTE

1. Your code will run on multiple test cases, please come up with an optimised solution.
2. Try to do it one pass through the trees.

INPUT FORMAT

A : Root of Tree A
B : Root of Tree B

EXAMPLE INPUT

Tree A:
    5
   / \
  2   8
   \   \
    3   15
        /
        7

Tree B:
    7
   / \
  1  10
   \   \
    2  15
       /
      8

EXAMPLE OUTPUT

38

EXAMPLE EXPLANATION

Common Nodes are : 2, 7, 8, 15
So answer is 2 + 7 + 8 + 15 = 32
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Common Nodes in Two Binary Search Trees on Interview Code Editor
Sign Up
to access hints and editorial solutions for Common Nodes in Two Binary Search Trees

Discussion


Loading...
Click here to start solving coding interview questions