Print all nodes at distance k from a given node

Given a binary tree, a target node in the binary tree, and an integer value k, print all the nodes that are at distance k from the given target node. No parent pointers are available

Consider the tree shown in diagram

Input: target = pointer to node with data 8.
       root = pointer to node with data 20.
       k = 2.
Output : 10 14 22

If target is 14 and k is 3, then output should be "4 20"

Print all nodes at distance k from a given node

from: http://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/

与该点相距k的点,分两种:

1. 在k的子树;

2. k回溯到前第d个点,然后从该点往左子树或者右子树求第k-d个点。

中序遍历,记录和target的距离。

每个点最多会被访问两次。所以还是O(n).

你可能感兴趣的:(print)