`

Find distance between two given keys of a Binary Tree

 
阅读更多

Find the distance between two keys in a binary tree, no parent pointers are given. Distance between two nodes is the minimum number of edges to be traversed to reach one node from other.

dist

 

The distance between two nodes can be obtained in terms of lowest common ancestor. Following is the formula.

Dist(n1, n2) = Dist(root, n1) + Dist(root, n2) - 2*Dist(root, lca) 
'n1' and 'n2' are the two given keys
'root' is root of given Binary Tree.
'lca' is lowest common ancestor of n1 and n2
Dist(n1, n2) is the distance between n1 and n2.

Following is C++ implementation of above approach. The implementation is adopted from last code provided in Lowest Common Ancestor Post.

/* Program to find distance between n1 and n2 using one traversal */
#include <iostream>
using namespace std;
 
// A Binary Tree Node
struct Node
{
    struct Node *left, *right;
    int key;
};
 
// Utility function to create a new tree Node
Node* newNode(int key)
{
    Node *temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Returns level of key k if it is present in tree, otherwise returns -1
int findLevel(Node *root, int k, int level)
{
    // Base Case
    if (root == NULL)
        return -1;
 
    // If key is present at root, or in left subtree or right subtree,
    // return true;
    if (root->key == k)
        return level;
 
    int l = findLevel(root->left, k, level+1);
    return (l != -1)? l : findLevel(root->right, k, level+1);
}
 
// This function returns pointer to LCA of two given values n1 and n2. 
// It also sets d1, d2 and dist if one key is not ancestor of other
// d1 --> To store distance of n1 from root
// d2 --> To store distance of n2 from root
// lvl --> Level (or distance from root) of current node
// dist --> To store distance between n1 and n2
Node *findDistUtil(Node* root, int n1, int n2, int &d1, int &d2, 
                   int &dist, int lvl)
{
    // Base case
    if (root == NULL) return NULL;
 
    // If either n1 or n2 matches with root's key, report
    // the presence by returning root (Note that if a key is
    // ancestor of other, then the ancestor key becomes LCA
    if (root->key == n1)
    {
         d1 = lvl;
         return root;
    }
    if (root->key == n2)
    {
         d2 = lvl;
         return root;
    }
 
    // Look for n1 and n2 in left and right subtrees
    Node *left_lca  = findDistUtil(root->left, n1, n2, d1, d2, dist, lvl+1);
    Node *right_lca = findDistUtil(root->right, n1, n2, d1, d2, dist, lvl+1);
 
    // If both of the above calls return Non-NULL, then one key
    // is present in once subtree and other is present in other,
    // So this node is the LCA
    if (left_lca && right_lca)
    {
        dist = d1 + d2 - 2*lvl;
        return root;
    }
 
    // Otherwise check if left subtree or right subtree is LCA
    return (left_lca != NULL)? left_lca: right_lca;
}
 
// The main function that returns distance between n1 and n2
// This function returns -1 if either n1 or n2 is not present in
// Binary Tree.
int findDistance(Node *root, int n1, int n2)
{
    // Initialize d1 (distance of n1 from root), d2 (distance of n2 
    // from root) and dist(distance between n1 and n2)
    int d1 = -1, d2 = -1, dist;
    Node *lca = findDistUtil(root, n1, n2, d1, d2, dist, 1);
 
    // If both n1 and n2 were present in Binary Tree, return dist
    if (d1 != -1 && d2 != -1)
        return dist;
 
    // If n1 is ancestor of n2, consider n1 as root and find level 
    // of n2 in subtree rooted with n1
    if (d1 != -1)
    {
        dist = findLevel(lca, n2, 0);
        return dist;
    }
 
    // If n2 is ancestor of n1, consider n2 as root and find level 
    // of n1 in subtree rooted with n2
    if (d2 != -1)
    {
        dist = findLevel(lca, n1, 0);
        return dist;
    }
 
    return -1;
}

Time Complexity: Time complexity of the above solution is O(n) as the method does a single tree traversal.

From:

http://www.geeksforgeeks.org/find-distance-two-given-nodes/

分享到:
评论

相关推荐

    C#资源库-binarytree

    标题"C#资源库-binarytree"指的是一个使用C#编程语言实现的二叉树数据结构的代码库。在软件开发中,二叉树是一种基础且重要的数据结构,它由节点构成,每个节点最多有两个子节点,通常称为左子节点和右子节点。这种...

    BinaryTree-BinaryTree

    BinaryTree-BinaryTree

    BinaryTree

    This is a binary tree search implementation.

    Construct Binary Tree from Preorder and Inorder Traversal

    Construct Binary Tree from Preorder and Inorder Traversal 根据先序,中序建立二叉树

    陈越、何钦铭-数据结构作业16:Complete Binary Search Tree完全二叉搜索树

    Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal ...

    BinaryTree二叉树实现

    二叉树是一种重要的数据结构,它在计算机科学中扮演着至关重要的角色,特别是在算法和...在二叉树的`BinaryTree`文件中,可能会包含这些操作的具体实现,通过阅读和理解这些代码,可以深入学习和掌握二叉树的相关知识。

    binarytree.rar

    二叉树是一种在计算机科学中广泛使用的数据结构,它的每个节点最多有两个子节点,通常称为左子节点和右...解压“binarytree.rar”,查看其中的文件,理解数据结构,并根据给定的描述编写代码,以实现二叉树的前序遍历。

    BinaryTree-源码.rar

    【标题】:“BinaryTree-源码.rar”是一个与二叉树相关的源代码压缩包,它可能包含各种二叉树数据结构的实现,如二叉搜索树、平衡二叉树(AVL树或红黑树)或者自定义的二叉树结构。这个压缩包可能为学习数据结构与...

    java-二叉树binaryTree

    在IT领域,二叉树(Binary Tree)是一种基础的数据结构,尤其在计算机科学中有着广泛的应用。二叉树是每个节点最多有两个子节点的树结构,通常分为左子节点和右子节点。在这个"java-二叉树binaryTree"主题中,我们将...

    陈越、何钦铭-数据结构作业11:Tree Traversals Again二叉树非递归遍历/栈遍历

    For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5...

    binary tree C语言算法

    在计算机科学中,二叉树(Binary Tree)是一种数据结构,每个节点最多有两个子节点,通常分为左子节点和右子节点。这种数据结构广泛应用于各种算法和问题解决,如搜索、排序、文件系统等。在C语言中实现二叉树,我们...

    BinaryTreeSort

    BinaryTreeSort的java实现,简单的二叉树排序

    Python-BinaryTree用于学习二叉树的Python库

    "Python-BinaryTree"是一个专门用于学习和操作二叉树的Python库,它提供了方便的API来创建、遍历和操作二叉树。 1. **二叉树的概念与类型** - 二叉树的基本概念:二叉树的每个节点包含一个值、一个指向左子树的...

    Search in a Binary Search Tree.zip

    在"Search in a Binary Search Tree"这个主题中,我们主要探讨如何在二叉搜索树中高效地进行查找操作。查找操作的目标是找到树中与给定值相匹配的节点。由于二叉搜索树的特性,我们可以采用分治策略来实现快速查找:...

    BinaryTree.cpp

    C++实现 操作函数包括先序、中序、后序遍历,求深度,深度、广度遍历 构建二叉树

    二叉树官方源码BinaryTree_src

    在给定的“二叉树官方源码BinaryTree_src”中,我们可以找到一系列与二叉树相关的源代码文件,这为理解和实现二叉树提供了宝贵的参考资料。 首先,我们看到一个名为"BinaryTreeDemo.clw"的文件,这可能是项目的工作...

    心希盼 C++ STL binaryTree

    对于“心希盼 binaryTree.doc”文档,很可能是对这种使用STL实现二叉树的详细教程或示例代码,可能涵盖了如何构建二叉树、执行各种操作以及解决实际问题的实例。通过阅读和理解这份文档,开发者能够深入理解如何结合...

    BinaryTree.h

    有序二叉树创建 有序二叉树查找 二叉树遍历 有序二叉树删除 类模版实现的有序二叉树

    Simple Binary Tree Class.zip_binary tree_tree

    在IT领域,二叉树(Binary Tree)是一种基础的数据结构,它由节点构成,每个节点最多有两个子节点,通常称为左子节点和右子节点。这个压缩包"Simple Binary Tree Class.zip"包含了实现简单二叉树类的相关文件,包括...

    BinaryTree.java

    二叉树的实现代码,我的博客“Java——二叉树的基础实现”的代码。 https://blog.csdn.net/J_fla/article/details/103236673

Global site tag (gtag.js) - Google Analytics