码迷,mamicode.com
首页 > 其他好文 > 详细

Print all nodes at distance k from a given node

时间:2014-11-09 23:30:26      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:des   blog   http   ar   sp   for   on   2014   log   

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

标签:des   blog   http   ar   sp   for   on   2014   log   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!