
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find distance from root to given node in a binary tree in C++
Consider we have a binary tree with few nodes. We have to find the distance between the root and another node u. suppose the tree is like below:
Now the distance between (root, 6) = 2, path length is 2, distance between (root, 8) = 3 etc.
To solve this problem, we will use a recursive approach to search the node at the left and right subtrees, and also update the lengths for each level.
Example
#include<iostream> using namespace std; class Node { public: int data; Node *left, *right; }; Node* getNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } int getDistance(Node *root, int x) { if (root == NULL) return -1; int dist = -1; if ((root->data == x) || (dist = getDistance(root->left, x)) >= 0 || (dist = getDistance(root->right, x)) >= 0) return dist + 1; return dist; } int main() { Node* root = getNode(1); root->left = getNode(2); root->right = getNode(3); root->left->left = getNode(4); root->left->right = getNode(5); root->right->left = getNode(6); root->right->right = getNode(7); root->right->left->right = getNode(8); cout <<"Distance from root to node 6 is: " << getDistance(root,6); cout << "\nDistance from root to node 8 is: " << getDistance(root,8); }
Output
Distance from root to node 6 is: 2 Distance from root to node 8 is: 3
- Related Articles
- Program to print path from root to a given node in a binary tree using C++
- Find mirror of a given node in Binary tree in C++
- Print Ancestors of a given node in Binary Tree in C++
- Find the Deepest Node in a Binary Tree in C++
- Deleting desired node from a Binary Search Tree in JavaScrip
- Program to find second deepest node in a binary tree in python
- Print ancestors of a given binary tree node without recursion in C++
- Program to find sibling value of a binary tree node in Python
- Program to find largest binary search subtree from a given tree in Python
- Find a Corresponding Node of a Binary Tree in a Clone of That Tree in C++
- Second Minimum Node In a Binary Tree in C++
- Find the node with minimum value in a Binary Search Tree in C++
- Find n-th node in Postorder traversal of a Binary Tree in C++
- Find n-th node in Preorder traversal of a Binary Tree in C++
- Program to find sum of longest sum path from root to leaf of a binary tree in Python

Advertisements