BST Node Distance

Binary Search Tree

Medium

Description

Given a list of numbers, construct a BST from it(you need to insert nodes one-by-one with the given order to get the BST) and find the distance between two given nodes.

If two nodes do not appear in the BST, return -1
We guarantee that there are no duplicate nodes in BST
The node distance means the number of edges between two nodes

Example

input:
numbers = [2,1,3]
node1 = 1
node2 = 3
output:
2

Analysis

思路:

@giesekus0903

(LintCode: Total runtime 419 ms; beats 86.80%)

另一种(稍不必要的复杂了)

@yuhzeng:

先建BST, 再找LCA,两个node的距离=dist(root, n1) + dist(root, n2) - 2*dist(root, LCA). 用 findPathFromRoot来找到这三个距离。 dist = path.size() -1.

Reference

https://www.geeksforgeeks.org/shortest-distance-between-two-nodes-in-bst/

Last updated

Was this helpful?