📌  相关文章
📜  使用 BFS 的二叉树每个节点到根节点的距离

📅  最后修改于: 2021-09-05 08:37:22             🧑  作者: Mango

给定一个由N 个节点组成的二叉树,其值在[1, N]范围内,任务是找到从根节点到树的每个节点的距离。

例子:

方法:该问题可以使用 BFS 技术解决。这个想法是利用这样一个事实,即从根到节点的距离等于二叉树中该节点的级别。请按照以下步骤解决问题:

  • 初始化一个队列,比如Q ,以存储树的每一层的节点。
  • 初始化一个数组,比如dist[] ,其中dist[i]存储从根节点到树的i节点的距离。
  • 使用 BFS 遍历树。对于遇到的每个i节点,将dist[i]更新为二叉树中该节点的级别。
  • 最后,打印dist[]数组。

下面是上述方法的实现:

C++
1
                 /  \
                2   3 
               / \   \
             4   5   6


Java
5
                 / \
               4    6
             /  \     
            3    7
          / \     
        1    2


Python3
// C++ program to implement
// the above approach
 
#include 
using namespace std;
struct Node {
 
    // Stores data value
    // of the node
    int data;
 
    // Stores left subtree
    // of a node
    Node* left;
 
    // Stores right subtree
    // of a node
    Node* right;
 
    Node(int x)
    {
 
        data = x;
        left = right = NULL;
    }
};
 
void findDistance(Node* root, int N)
{
 
    // Store nodes at each level
    // of the binary tree
    queue Q;
 
    // Insert root into Q
    Q.push(root);
 
    // Stores level of a node
    int level = 0;
 
    // dist[i]: Stores the distance
    // from root node to node i
    int dist[N + 1];
 
    // Traverse tree using BFS
    while (!Q.empty()) {
 
        // Stores count of nodes
        // at current level
        int M = Q.size();
 
        // Traverse the nodes at
        // current level
        for (int i = 0; i < M; i++) {
 
            // Stores front element
            // of the queue
            root = Q.front();
 
            // Pop front element
            // of the queue
            Q.pop();
 
            // Stores the distance from
            // root node to current node
            dist[root->data] = level;
 
            if (root->left) {
 
                // Push left subtree
                Q.push(root->left);
            }
 
            if (root->right) {
 
                // Push right subtree
                Q.push(root->right);
            }
        }
 
        // Update level
        level += 1;
    }
 
    for (int i = 1; i <= N; i++) {
 
        cout << dist[i] << " ";
    }
}
 
// Driver Code
int main()
{
 
    int N = 7;
    Node* root = new Node(5);
    root->left = new Node(4);
    root->right = new Node(6);
    root->left->left = new Node(3);
    root->left->right = new Node(7);
    root->left->left->left = new Node(1);
    root->left->left->right = new Node(2);
    findDistance(root, N);
}


C#
// Java program to implement
// the above approach
import java.util.*;
 
class GFG
{
static class Node
{
 
    // Stores data value
    // of the node
    int data;
 
    // Stores left subtree
    // of a node
    Node left;
 
    // Stores right subtree
    // of a node
    Node right;
    Node(int x)
    {
        data = x;
        left = right = null;
    }
};
 
static void findDistance(Node root, int N)
{
 
    // Store nodes at each level
    // of the binary tree
    Queue Q = new LinkedList<>();
 
    // Insert root into Q
    Q.add(root);
 
    // Stores level of a node
    int level = 0;
 
    // dist[i]: Stores the distance
    // from root node to node i
    int []dist = new int[N + 1];
 
    // Traverse tree using BFS
    while (!Q.isEmpty())
    {
 
        // Stores count of nodes
        // at current level
        int M = Q.size();
 
        // Traverse the nodes at
        // current level
        for (int i = 0; i < M; i++)
        {
 
            // Stores front element
            // of the queue
            root = Q.peek();
 
            // Pop front element
            // of the queue
            Q.remove();
 
            // Stores the distance from
            // root node to current node
            dist[root.data] = level;
 
            if (root.left != null)
            {
 
                // Push left subtree
                Q.add(root.left);
            }
 
            if (root.right != null)
            {
 
                // Push right subtree
                Q.add(root.right);
            }
        }
 
        // Update level
        level += 1;
    }
 
    for (int i = 1; i <= N; i++)
    {
        System.out.print(dist[i] + " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
 
    int N = 7;
    Node root = new Node(5);
    root.left = new Node(4);
    root.right = new Node(6);
    root.left.left = new Node(3);
    root.left.right = new Node(7);
    root.left.left.left = new Node(1);
    root.left.left.right = new Node(2);
    findDistance(root, N);
}
}
 
// This code is contributed by shikhasingrajput


输出:
# Python3 program to implement
# the above approach
class Node:
     
    def __init__(self, data):
         
        # Stores data value
        # of the node
        self.data = data
         
        # Stores left subtree
        # of a node
        self.left = None
         
        # Stores right subtree
        # of a node
        self.right = None
 
def findDistance(root, N):
     
    # Store nodes at each level
    # of the binary tree
    Q = []
     
    # Insert root into Q
    Q.append(root)
     
    # Stores level of a node
    level = 0
     
    # dist[i]: Stores the distance
    # from root node to node i
    dist = [0 for i in range(N + 1)]
     
    # Traverse tree using BFS
    while Q:
         
        # Stores count of nodes
        # at current level
        M = len(Q)
         
        # Traverse the nodes at
        # current level
        for i in range(0, M):
             
            # Stores front element
            # of the queue
            root = Q[0]
             
            # Pop front element
            # of the queue
            Q.pop(0)
             
            #  Stores the distance from
            # root node to current node
            dist[root.data] = level
             
            if root.left:
                 
                # Push left subtree
                Q.append(root.left)
            if root.right:
                 
                # Push right subtree
                Q.append(root.right)
                 
        # Update level
        level += 1
         
    for i in range(1, N + 1):
        print(dist[i], end = " ")
 
# Driver code
if __name__ == '__main__':
     
    N = 7
    root = Node(5)
    root.left = Node(4)
    root.right = Node(6)
    root.left.left = Node(3)
    root.left.right = Node(7)
    root.left.left.left = Node(1)
    root.left.left.right = Node(2)
     
    findDistance(root, N)
 
# This code is contributed by MuskanKalra1

时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live