BST Node Distance(递归和树)
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
Have you met this question in a real interview?
Yes
Problem Correction
Example
分析
1.建树,用每个Node insert:注意这里root直接传入的话不会赋值,只能return root才行
2.最近公共parent,LCA然后到parent的dist1+dist2
注意这里超时,所以是在lca里直接得到距离。> root 去右 <root去左,一大一小root是LCA,用getrootdist。
3.getrootdist用递归,注意这里找不到node返回无穷大。这样没有的话<0结果就返回-1
refer to:https://www.geeksforgeeks.org/shortest-distance-between-two-nodes-in-bst/
Last updated