Given a Binary Tree and a positive integer k, print all nodes that are distance k from a leaf node.
Here the meaning of distance is different from previous post. Here k distance from a leaf means k levels higher than a leaf node. For example if k is more than height of Binary Tree, then nothing should be printed. Expected time complexity is O(n) where n is the number nodes in the given Binary Tree.
The idea is to traverse the tree. Keep storing all ancestors till we hit a leaf node. When we reach a leaf node, we print the ancestor at distance k. We also need to keep track of nodes that are already printed as output. For that we use a boolean array visited[].
/* Program to print all nodes which are at distance k from a leaf */ #include <iostream> using namespace std; #define MAX_HEIGHT 10000 struct Node { int key; Node *left, *right; }; /* utility that allocates a new Node with the given key */ Node* newNode(int key) { Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node); } /* This function prints all nodes that are distance k from a leaf node path[] --> Store ancestors of a node visited[] --> Stores true if a node is printed as output. A node may be k distance away from many leaves, we want to print it once */ void kDistantFromLeafUtil(Node* node, int path[], bool visited[], int pathLen, int k) { // Base case if (node==NULL) return; /* append this Node to the path array */ path[pathLen] = node->key; visited[pathLen] = false; pathLen++; /* it's a leaf, so print the ancestor at distance k only if the ancestor is not already printed */ if (node->left == NULL && node->right == NULL && pathLen-k-1 >= 0 && visited[pathLen-k-1] == false) { cout << path[pathLen-k-1] << " "; visited[pathLen-k-1] = true; return; } /* If not leaf node, recur for left and right subtrees */ kDistantFromLeafUtil(node->left, path, visited, pathLen, k); kDistantFromLeafUtil(node->right, path, visited, pathLen, k); } /* Given a binary tree and a nuber k, print all nodes that are k distant from a leaf*/ void printKDistantfromLeaf(Node* node, int k) { int path[MAX_HEIGHT]; bool visited[MAX_HEIGHT] = {false}; kDistantFromLeafUtil(node, path, visited, 0, k); } /* Driver program to test above functions*/ int main() { // Let us create binary tree given in the above example Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); cout << "Nodes at distance 2 are: "; printKDistantfromLeaf(root, 2); return 0; }
Output:
Nodes at distance 2 are: 3 1
Time Complexity: Time Complexity of above code is O(n) as the code does a simple tree traversal.
From:
http://www.geeksforgeeks.org/print-nodes-distance-k-leaf-node/
相关推荐
java基础 java_leetcode题解之All Nodes Distance K in Binary Tree.java
that target a single node (for example, all nodes in the botnet might be commanded by the attacker to send a TCP SYN message to the target, which might result in a TCP SYN flood attack at the target)...
对于nodes.dat文件,相关的操作可能包括“ping”(检查节点是否在线)、“find_node”(查找与特定ID最接近的节点)和“store”(存储键值对到网络中)。通过分析这些报文,我们可以找出哪些节点在互相交换nodes.dat...
captioning, speech synthesis, and music generation all require that a model produce outputs that are sequences. In other domains, such as time series prediction, video analysis, and musical ...
AcpiExResolveObjectToValue during a read from a buffer or region field. (BZ 458) Fiodor Suietov. Example Code and Data Size: These are the sizes for the OS- independent acpica.lib produced by the ...
distance.m : This is a function that calculates the distance between 2 nodes. min_fn.m : This function takes the list OPEN as one of its arguments and returns the node with the smallest cost ...
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 ...
lru缓存leetcode 使用 Javascript 的算法 问题陈述 在 Javascript 中实现 LRU 缓存、深度优先搜索和广度优先搜索。...a ...from a ...node ...node) ...nodes. ...are visited. - The first node that is visited compl
这个"count-leaf-nodes.rar_count leaf_countleaf"的压缩包文件显然涉及到与树相关的两个操作:计算叶子节点的数量以及交换二叉树的左右子树。 首先,让我们详细探讨如何**计算叶子节点**(也称为终端节点)的数量...
标题"wsn-topology.zip_wsn nodes_wsn节点分布_网络拓扑_节点分布_节点随机"表明,这个压缩包可能包含关于WSN节点分布和网络拓扑的详细资料,特别是关于节点随机分布的研究。 在WSN中,网络拓扑是指节点间物理连接...
Ensure that the necessary driver files are all present in the directory from which HINTON.EXE is run: HINTON.EXE EGAVGA.BGI CGA.BGI Use To use the program, at the DOS prompt type: hinton {...
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right. Now given a sequence of distinct non-negative ...
mldonkey需要的nodes.dat
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right. Now given a sequence of distinct non-negative ...
In a steady state, a node maintains information about \(\Theta(\log N)\) other nodes and resolves all lookups via \(\Theta(\log N)\) messages. When nodes join or leave the system, Chord maintains ...
BayesUpdating.py: computing the a-posteriori probability of a node given the probabilities of its parents. InputNode.py: class definition for "input nodes". InputNode is a subclass of BayesNetNode....