📌  相关文章
📜  为二叉树的每个节点计算具有较小值的祖先

📅  最后修改于: 2021-09-04 08:33:27             🧑  作者: Mango

给定一个由N 个节点组成的二叉树,值从1N ,以节点1为根,每个节点的任务是计算值小于当前节点的祖先的数量。

例子:

做法:思路是从Tree的根节点开始进行DFS遍历,将每个节点的直接父节点存储在一个数组中。然后迭代每个节点并使用父数组,将其值与其所有祖先进行比较。最后,打印结果。
请按照以下步骤解决问题:

  • -1初始化一个数组,比如大小为N 的par[] ,以存储每个节点的直接父节点。
  • 从根节点进行DFS遍历,执行以下步骤:
    • 更新当前节点的父节点。
    • 递归调用当前节点的子节点。
  • 现在,使用变量i迭代范围[1, N]并执行以下步骤:
    • 将当前节点存储在一个变量中,比如node
    • par[node]不等于-1 时进行迭代:
      • 如果par[node]小于i ,则将cnt增加1
      • 节点更新为par[node]
    • 完成以上步骤后,打印cnt的值作为当前节点的值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to add an edge
// between nodes u and v
void add_edge(vector adj[],
              int u, int v)
{
    adj[u].push_back(v);
    adj[v].push_back(u);
}
 
// Function to perform the DFS Traversal
// and store parent of each node
void dfs(vector& parent,
         vector adj[],
         int u,
         int par = -1)
{
    // Store the immediate parent
    parent[u] = par;
 
    // Traverse the children of
    // the current node
    for (auto child : adj[u]) {
 
        // Recursively call for
        // function dfs for the
        // child node
        if (child != par)
            dfs(parent, adj, child, u);
    }
}
 
// Function to count the number of
// ancestors with values smaller
// than that of the current node
void countSmallerAncestors(
    vector adj[], int n)
{
    // Stores the parent of each node
    vector parent(int(1e5), 0);
 
    // Perform the DFS Traversal
    dfs(parent, adj, 1);
 
    // Traverse all the nodes
    for (int i = 1; i <= n; i++) {
 
        int node = i;
 
        // Store the number of ancestors
        // smaller than node
        int cnt = 0;
 
        // Loop until parent[node] != -1
        while (parent[node] != -1) {
 
            // If the condition satisfies,
            // increment cnt by 1
            if (parent[node] < i)
                cnt += 1;
 
            node = parent[node];
        }
 
        // Print the required result
        // for the current node
        cout << cnt << " ";
    }
}
 
// Driver Code
int main()
{
    int N = 6;
    vector adj[int(1e5)];
 
    // Tree Formation
    add_edge(adj, 1, 5);
    add_edge(adj, 1, 4);
    add_edge(adj, 4, 6);
    add_edge(adj, 5, 3);
    add_edge(adj, 5, 2);
 
    countSmallerAncestors(adj, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to add an edge
// between nodes u and v
static void add_edge(ArrayList> adj,
                     int u, int v)
{
    adj.get(u).add(v);
    adj.get(v).add(u);
}
   
// Function to perform the DFS Traversal
// and store parent of each node
static void dfs(ArrayList parent,
                ArrayList> adj,
                int u, int par)
{
     
    // Store the immediate parent
    parent.set(u,par);
   
    // Traverse the children of
    // the current node
    for(int child : adj.get(u))
    {
         
        // Recursively call for
        // function dfs for the
        // child node
        if (child != par)
            dfs(parent, adj, child, u);
    }
}
   
// Function to count the number of
// ancestors with values smaller
// than that of the current node
static void countSmallerAncestors(
    ArrayList> adj, int n)
{
     
    // Stores the parent of each node
    ArrayList parent = new ArrayList();
    for(int i = 0; i < (int)(1e5); i++)
    {
        parent.add(0);
    }
   
    // Perform the DFS Traversal
    dfs(parent, adj, 1, -1);
   
    // Traverse all the nodes
    for(int i = 1; i <= n; i++)
    {
        int node = i;
   
        // Store the number of ancestors
        // smaller than node
        int cnt = 0;
   
        // Loop until parent[node] != -1
        while (parent.get(node) != -1)
        {
             
            // If the condition satisfies,
            // increment cnt by 1
            if (parent.get(node) < i)
                cnt += 1;
   
            node = parent.get(node);
        }
   
        // Print the required result
        // for the current node
        System.out.print(cnt + " ");
    }
}
 
// Driver code
public static void main (String[] args)
{
    int N = 6;
    ArrayList> adj = new ArrayList>();
    for(int i = 0; i < (int)(1e5); i++)
    {
        adj.add(new ArrayList());
    }
   
    // Tree Formation
    add_edge(adj, 1, 5);
    add_edge(adj, 1, 4);
    add_edge(adj, 4, 6);
    add_edge(adj, 5, 3);
    add_edge(adj, 5, 2);
   
    countSmallerAncestors(adj, N);
}
}
 
// This code is contributed by avanitrachhadiya2155


Python3
# Python3 program for the above approach
 
# Function to add an edge
# between nodes u and v
def add_edge(u, v):
     
    global adj
    adj[u].append(v)
    adj[v].append(u)
 
# Function to perform the DFS Traversal
# and store parent of each node
def dfs(u, par = -1):
     
    global adj, parent
     
    # Store the immediate parent
    parent[u] = par
 
    # Traverse the children of
    # the current node
    for child in adj[u]:
         
        # Recursively call for
        # function dfs for the
        # child node
        if (child != par):
            dfs(child, u)
 
# Function to count the number of
# ancestors with values smaller
# than that of the current node
def countSmallerAncestors(n):
     
    global parent, adj
     
    # Stores the parent of each node
 
    # Perform the DFS Traversal
    dfs(1)
 
    # Traverse all the nodes
    for i in range(1, n + 1):
        node = i
 
        # Store the number of ancestors
        # smaller than node
        cnt = 0
 
        # Loop until parent[node] != -1
        while (parent[node] != -1):
             
            # If the condition satisfies,
            # increment cnt by 1
            if (parent[node] < i):
                cnt += 1
 
            node = parent[node]
 
        # Print the required result
        # for the current node
        print(cnt, end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    N = 6
    adj = [[] for i in range(10**5)]
    parent = [0] * (10**5)
 
    # Tree Formation
    add_edge(1, 5)
    add_edge(1, 4)
    add_edge(4, 6)
    add_edge(5, 3)
    add_edge(5, 2)
 
    countSmallerAncestors(N)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to add an edge
    // between nodes u and v
    static void add_edge(List> adj, int u, int v)
    {
        adj[u].Add(v);
        adj[v].Add(u);
    }
      
    // Function to perform the DFS Traversal
    // and store parent of each node
    static void dfs(List parent,
             List> adj,
             int u,
             int par = -1)
    {
        // Store the immediate parent
        parent[u] = par;
      
        // Traverse the children of
        // the current node
        foreach(int child in adj[u]) {
      
            // Recursively call for
            // function dfs for the
            // child node
            if (child != par)
                dfs(parent, adj, child, u);
        }
    }
      
    // Function to count the number of
    // ancestors with values smaller
    // than that of the current node
    static void countSmallerAncestors(
        List> adj, int n)
    {
        // Stores the parent of each node
        List parent = new List();
        for(int i = 0; i < (int)(1e5); i++)
        {
            parent.Add(0);
        }
      
        // Perform the DFS Traversal
        dfs(parent, adj, 1);
      
        // Traverse all the nodes
        for (int i = 1; i <= n; i++) {
      
            int node = i;
      
            // Store the number of ancestors
            // smaller than node
            int cnt = 0;
      
            // Loop until parent[node] != -1
            while (parent[node] != -1) {
      
                // If the condition satisfies,
                // increment cnt by 1
                if (parent[node] < i)
                    cnt += 1;
      
                node = parent[node];
            }
      
            // Print the required result
            // for the current node
            Console.Write(cnt + " ");
        }
    }
 
  static void Main() {
    int N = 6;
    List> adj = new List>();
    for(int i = 0; i < (int)(1e5); i++)
    {
        adj.Add(new List());
    }
  
    // Tree Formation
    add_edge(adj, 1, 5);
    add_edge(adj, 1, 4);
    add_edge(adj, 4, 6);
    add_edge(adj, 5, 3);
    add_edge(adj, 5, 2);
  
    countSmallerAncestors(adj, N);
  }
}


Javascript


输出:
0 1 1 1 1 2

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

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