Найти родителя узла в данном двоичном дереве
Учитывая дерево и узел, задача состоит в том, чтобы найти в дереве родителя данного узла. Выведите -1, если данный узел является корневым.
Примеры:
Ввод: Узел = 3 1 / 2 3 / 4 5 Выход: 1 Вход: узел = 1 1 / 2 3 / 4 5 / 6 Выход: -1
Approach: Write a recursive function that takes the current node and its parent as the arguments (root node is passed with -1 as its parent). If the current node is equal to the required node then print its parent and return else call the function recursively for its children and the current node as the parent.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <iostream> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; Node( int data) { this ->data = data; left = right = NULL; } }; // Recursive function to find the // parent of the given node void findParent( struct Node* node, int val, int parent) { if (node == NULL) return ; // If current node is the required node if (node->data == val) { // Print its parent cout << parent; } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node->left, val, node->data); findParent(node->right, val, node->data); } } // Driver code int main() { struct Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); int node = 3; findParent(root, node, -1); return 0; } |
Java
// Java implementation of the approach class GFG { /* A binary tree node has data, pointer to left child and a pointer to right child */ static class Node { int data; Node left, right; Node( int data) { this .data = data; left = right = null ; } }; // Recursive function to find the // parent of the given node static void findParent(Node node, int val, int parent) { if (node == null ) return ; // If current node is the required node if (node.data == val) { // Print its parent System.out.print(parent); } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node.left, val, node.data); findParent(node.right, val, node.data); } } // Driver code public static void main(String []args) { Node root = new Node( 1 ); root.left = new Node( 2 ); root.right = new Node( 3 ); root.left.left = new Node( 4 ); root.left.right = new Node( 5 ); int node = 3 ; findParent(root, node, - 1 ); } } // This code is contributed by 29AjayKumar |
Python3
# Python3 implementation of # the above approach """ A binary tree node has data, pointer to left child and a pointer to right child """ class Node: def __init__( self , data): self .data = data self .left = None self .right = None # Recursive function to find the # parent of the given node def findParent(node : Node, val : int , parent : int ) - > None : if (node is None ): return # If current node is # the required node if (node.data = = val): # Print its parent print (parent) else : # Recursive calls # for the children # of the current node # Current node is now # the new parent findParent(node.left, val, node.data) findParent(node.right, val, node.data) # Driver code if __name__ = = "__main__" : root = Node( 1 ) root.left = Node( 2 ) root.right = Node( 3 ) root.left.left = Node( 4 ) root.left.right = Node( 5 ) node = 3 findParent(root, node, - 1 ) # This code is contributed by sanjeev2552 |
C#
// C# implementation of the approach using System; class GFG { /* A binary tree node has data, pointer to left child and a pointer to right child */ public class Node { public int data; public Node left, right; public Node( int data) { this .data = data; left = right = null ; } }; // Recursive function to find the // parent of the given node static void findParent(Node node, int val, int parent) { if (node == null ) return ; // If current node is the required node if (node.data == val) { // Print its parent Console.Write(parent); } else { // Recursive calls for the children // of the current node // Current node is now the new parent findParent(node.left, val, node.data); findParent(node.right, val, node.data); } } // Driver code public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); int node = 3; findParent(root, node, -1); } } // This code is contributed by Rajput-Ji |
1
Вниманию читателя! Не прекращайте учиться сейчас. Освойте все важные концепции DSA с помощью самостоятельного курса DSA по приемлемой для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .
Если вы хотите посещать живые занятия с отраслевыми экспертами, пожалуйста, обращайтесь к Geeks Classes Live и Geeks Classes Live USA.