`

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.

BinaryTree

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"


 

There are two types of nodes to be considered.
1) Nodes in the subtree rooted with target node. For example if the target node is 8 and k is 2, then such nodes are 10 and 14.
2) Other nodes, may be an ancestor of target, or a node in some other subtree. For target node 8 and k is 2, the node 22 comes in this category.

Finding the first type of nodes is easy to implement. Just traverse subtrees rooted with the target node and decrement k in recursive call. When the k becomes 0, print the node currently being traversed (See this for more details). Here we call the function as printkdistanceNodeDown().

How to find nodes of second type? For the output nodes not lying in the subtree with the target node as the root, we must go through all ancestors. For every ancestor, we find its distance from target node, let the distance be d, now we go to other subtree (if target was found in left subtree, then we go to right subtree and vice versa) of the ancestor and find all nodes at k-d distance from the ancestor.

Following is C++ implementation of the above approach.

#include <iostream>
using namespace std;
 
// A binary Tree node
struct node {
    int data;
    struct node *left, *right;
};
 
/* Recursive function to print all the nodes at distance k in the
   tree (or subtree) rooted with given root. See  */
void printkdistanceNodeDown(node *root, int k)
{
    // Base Case
    if (root == NULL || k < 0)  return;
 
    // If we reach a k distant node, print it
    if (k==0)
    {
        cout << root->data << endl;
        return;
    }
 
    // Recur for left and right subtrees
    printkdistanceNodeDown(root->left, k-1);
    printkdistanceNodeDown(root->right, k-1);
}
 
// Prints all nodes at distance k from a given target node.
// The k distant nodes may be upward or downward.  This function
// Returns distance of root from target node, it returns -1 if target
// node is not present in tree rooted with root.
int printkdistanceNode(node* root, node* target , int k)
{
    // Base Case 1: If tree is empty, return -1
    if (root == NULL) return -1;
 
    // If target is same as root.  Use the downward function
    // to print all nodes at distance k in subtree rooted with
    // target or root
    if (root == target)
    {
        printkdistanceNodeDown(root, k);
        return 0;
    }
 
    // Recur for left subtree
    int dl = printkdistanceNode(root->left, target, k);
 
    // Check if target node was found in left subtree
    if (dl != -1)
    {
         // If root is at distance k from target, print root
         // Note that dl is Distance of root's left child from target
         if (dl + 1 == k)
            cout << root->data << endl;
 
         // Else go to right subtree and print all k-dl-2 distant nodes
         // Note that the right child is 2 edges away from left child
         else
            printkdistanceNodeDown(root->right, k-dl-2);
 
         // Add 1 to the distance and return value for parent calls
         return 1 + dl;
    }
 
    // MIRROR OF ABOVE CODE FOR RIGHT SUBTREE
    // Note that we reach here only when node was not found in left subtree
    int dr = printkdistanceNode(root->right, target, k);
    if (dr != -1)
    {
         if (dr + 1 == k)
            cout << root->data << endl;
         else
            printkdistanceNodeDown(root->left, k-dr-2);
         return 1 + dr;
    }
 
    // If target was neither present in left nor in right subtree
    return -1;
}

Time Complexity: At first look the time complexity looks more than O(n), but if we take a closer look, we can observe that no node is traversed more than twice. Therefore the time complexity is O(n).

From:

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

分享到:
评论

相关推荐

    java-leetcode题解之All Nodes Distance K in Binary Tree.java

    java基础 java_leetcode题解之All Nodes Distance K in Binary Tree.java

    Distr_Nodes.rar_Distr_Nodes_distance vector_距离向量_距离向量算法_选路

    本项目"**Distr_Nodes.rar**"即为一个C语言实现的距离向量算法的实例,旨在帮助我们理解并掌握这种算法的运作机制。 距离向量算法,又称为贝尔曼-福特(Bellman-Ford)算法,其核心思想是通过不断交换节点间的距离...

    mldonkey需要的nodes.dat

    mldonkey需要的nodes.dat

    kad协议里的nodes.dat文件抓包详解

    对于nodes.dat文件,相关的操作可能包括“ping”(检查节点是否在线)、“find_node”(查找与特定ID最接近的节点)和“store”(存储键值对到网络中)。通过分析这些报文,我们可以找出哪些节点在互相交换nodes.dat...

    update-nodes:更新推荐的Node.js版本

    标题中的"update-nodes:更新推荐的Node.js版本"指的是一个用于自动化Node.js版本升级的工具。这个工具简化了管理不同项目中Node.js版本的过程,确保你始终能够运行最新且被推荐的稳定版本。 描述中提到的"注意: 是...

    PowerCommands for Visual Studio 2008

    It can be executed from the references node, a single reference node or set of reference nodes. Paste References This command pastes a reference or set of references from the clipboard. It can be ...

    wsn-topology.zip_wsn nodes_wsn节点分布_网络拓扑_节点分布_节点随机

    标题"wsn-topology.zip_wsn nodes_wsn节点分布_网络拓扑_节点分布_节点随机"表明,这个压缩包可能包含关于WSN节点分布和网络拓扑的详细资料,特别是关于节点随机分布的研究。 在WSN中,网络拓扑是指节点间物理连接...

    lrucacheleetcode-BSF-DSF-LRU-Using-[removed]BSF-DSF-LRU-Using-Javascr

    a traversing algorithm where you should start traversing from a selected node (source or starting node) and traverse the graph layerwise thus exploring the neighbour nodes. - We start from a node and ...

    node10.15.3有64位与32位msi安装版

    Node.js 是一个开源的、跨平台的 JavaScript 运行环境,它允许开发者在服务器端运行 JavaScript 代码。Node.js 的版本管理对于开发人员来说非常重要,因为它确保了项目的依赖性得到满足,同时也方便了不同版本之间的...

    node-red-nodes:Node-RED的额外节点

    cd ~/.node-red npm install node-red-node-{filename} 要使用此存储库手动安装: cd进入Node-RED的nodes目录任何一个: 下载存储库的zip并将其解压缩运行git clone https://github.com/node-red/node-red-nodes.git ...

    Matlab有限元网格化源程序-ddd.m

    signed distance from each node location p to the closest boundary. • The desired edge length function h is given as a function fh, which returns h for all input points. • The parameter h0 is the ...

    node-worker-nodes:一个node.js库,用于在单独的进程中运行CPU密集型任务,而不阻塞事件循环

    安装$ npm install worker-nodes 需要大于11.7.0的Node.jsAPI参考工作节点种类:全球舱 : Proxy ⇒ Promise ⇒ Promise ⇒ void ⇒ void ⇒ Array.新的WorkerNodes(路径,[选项]) 参数类型描述路径String 将在...

    Matlab有限元网格化源程序-huniform.m

    signed distance from each node location p to the closest boundary. • The desired edge length function h is given as a function fh, which returns h for all input points. • The parameter h0 is the ...

    Matlab有限元网格化源程序-dcircle.m

    signed distance from each node location p to the closest boundary. • The desired edge length function h is given as a function fh, which returns h for all input points. • The parameter h0 is the ...

    Matlab有限元网格化源程序-distmesh2d.m

    signed distance from each node location p to the closest boundary. • The desired edge length function h is given as a function fh, which returns h for all input points. • The parameter h0 is the ...

    CBST.rar_The Keys_bst

    The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than or equal to the node's key. Both the left ...

    node-red .zip

    Node-RED是一款基于Node.js的可视化编程工具,用于构建物联网(IoT)应用。它将复杂的编程任务简化为连接各种预定义的“节点”(nodes),使得非程序员也能轻松实现设备间的数据流处理。在“node-red .zip”这个压缩包...

    node+layui后台管理系统.zip

    《基于Node.js与Layui的后台管理系统详解》 在当今的互联网开发中,后台管理系统是企业运营不可或缺的一部分,它负责处理数据、监控系统状态、提供管理界面等关键任务。本篇文章将深入探讨一个基于Node.js和Layui...

Global site tag (gtag.js) - Google Analytics