简体   繁体   中英

nearest leaf node from given node in binary tree

Find the nearest leaf node from given node in binary tree.

if the tree is :

                      1

                2         3

           4       5

       6        7

   9        8

than the shortest leaf node from 2 is 3. Can somebody help me is devising an algo for this. Thanks.

I am able to find if the node is root node ( by simple DFS) but not able to device an algo for this case where the node is not the ancestor of the shortest distant leaf node.

Tree representation :

Class TreeNode{
    int val;
    TreeNode left, right;
}

You are given with a Node ie t1 and root ie t .

1) find the leaf closest to the root of the tree (DFS)

2) find the depth of the given node, if you don't know it already (DFS)

3) find the leaf closest to the given node among its descendants (DFS)

The solution is the shortest among 1+2 and 3. It can probably be combined in a single DFS.

As pointed by @Eyal, this is wrong.

Here is the fix:

1) For every node in the tree, find the closest leaf among its descendants (DFS).

2) For every node along the path from the root of the tree to the given node, add the distance from the node to its closest descendant and the distance to the given node.

A solution is given by the smallest sum.

You can implement this as follows:

  • Start from the DFS algorithm that finds a closest descendant leaf for all nodes in the tree.

  • Modify the recursive function so that it knows a) the depth of the current node, let Dc, b) the depth of the given node, let Dg, and c) the smallest depth reached since the given node was seen, let Ds, initially set to -1, d) the closest node so far (not necessarily a descendant).

  • Before leaving the function, if the current node is the given node, set Dg= Ds= Dc; else if Dc < Ds, update Ds= Dc and keep the closest node between the closest so far and the closest descendant of the current node, adding a distance penalty Dc - Dg.

In order to find the closest node in an unweighted graph you need to perform BFS. The adjacent nodes of a given node are all its child nodes and its predecessor(if any). You will have to choose an appropriate representation of the tree so that you can find the predecessor of a given node as well as its child nodes.

Also note that for this problem you will have to consider the graph as undirected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM