首页 > 其他 > 详细

Print all nodes at distance k from a given node

时间:2014-11-09 23:27:40      阅读:313      评论:0      收藏:0      [点我收藏+]

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"

bubuko.com,布布扣

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 all nodes at distance k from a given node

原文:http://www.cnblogs.com/linyx/p/4086017.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!