📌  相关文章
📜  节点的最大节点数小于其子树中的值

📅  最后修改于: 2021-09-06 06:39:39             🧑  作者: Mango

给定一棵二叉树,任务是从给定的树中找到其子树中具有最大节点数且值小于该节点值的节点。如果多个可能的节点具有相同的最大节点数,则返回任何此类节点。

例子:

方法:想法是使用后序遍历。以下是步骤:

  1. 在给定的树上执行后序遍历。
  2. 将左子树和右子树的节点与其根值进行比较,如果小于根值,则存储小于根节点的节点。
  3. 在每个节点上使用上述步骤,找到节点数,然后选择键小于当前节点的节点数最大的节点。
  4. 在上述遍历之后,打印最大计数的节点,其节点值小于该节点。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Stores the nodes to be deleted
unordered_map mp;
 
// Structure of a Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Function to compare the current node
// key with keys received from it left
// & right tree by Post Order traversal
vector findNodes(Node* root, int& max_v,
                      int& rootIndex)
{
    // Base Case
    if (!root) {
        return vector{};
    }
 
    // Find nodes lesser than the current
    // root in the left subtree
    vector left
        = findNodes(root->left, max_v,
                    rootIndex);
 
    // Find nodes lesser than the current
    // root in the right subtree
    vector right
        = findNodes(root->right, max_v,
                    rootIndex);
 
    // Stores all the nodes less than
    // the current node's
    vector combined;
    int count = 0;
 
    // Add the nodes which are less
    // than current node in left[]
    for (int i = 0;
         i < left.size(); i++) {
 
        if (left[i] < root->key) {
            count += 1;
        }
        combined.push_back(left[i]);
    }
 
    // Add the nodes which are less
    // than current node in right[]
    for (int i = 0;
         i < right.size(); i++) {
 
        if (right[i] < root->key) {
            count += 1;
        }
        combined.push_back(right[i]);
    }
 
    // Create a combined vector for
    // pass to it's parent
    combined.push_back(root->key);
 
    // Stores key that has maximum nodes
    if (count > max_v) {
        rootIndex = root->key;
        max_v = count;
    }
 
    // Return the vector of nodes
    return combined;
}
 
// Driver Code
int main()
{
    /*
              3
           /     \
           4        6
         /  \     /   \
       10    2   4     5
    */
 
    // Given Tree
    Node* root = newNode(3);
    root->left = newNode(4);
    root->right = newNode(6);
    root->right->left = newNode(4);
    root->right->right = newNode(5);
    root->left->left = newNode(10);
    root->left->right = newNode(2);
 
    int max_v = 0;
    int rootIndex = -1;
 
    // Function Call
    findNodes(root, max_v, rootIndex);
 
    // Print the node value
    cout << rootIndex;
}


Java
// Java program for
// the above approach
import java.util.*;
class GFG{
 
// Stores the nodes to be deleted
static HashMap mp = new HashMap();
static int max_v, rootIndex;
// Structure of a Tree node
static class Node
{
  int key;
  Node left, right;
};
 
// Function to create a new node
static Node newNode(int key)
{
  Node temp = new Node();
  temp.key = key;
  temp.left = temp.right = null;
  return (temp);
}
 
// Function to compare the current node
// key with keys received from it left
// & right tree by Post Order traversal
static Vector findNodes(Node root)
{
  // Base Case
  if (root == null)
  {
    return new Vector();
  }
 
  // Find nodes lesser than the current
  // root in the left subtree
  Vector left = findNodes(root.left);
 
  // Find nodes lesser than the current
  // root in the right subtree
  Vector right = findNodes(root.right);
 
  // Stores all the nodes less than
  // the current node's
  Vector combined = new Vector();
  int count = 0;
 
  // Add the nodes which are less
  // than current node in left[]
  for (int i = 0; i < left.size(); i++)
  {
    if (left.get(i) < root.key)
    {
      count += 1;
    }
    combined.add(left.get(i));
  }
 
  // Add the nodes which are less
  // than current node in right[]
  for (int i = 0; i < right.size(); i++)
  {
    if (right.get(i) < root.key)
    {
      count += 1;
    }
    combined.add(right.get(i));
  }
 
  // Create a combined vector for
  // pass to it's parent
  combined.add(root.key);
 
  // Stores key that has maximum nodes
  if (count > max_v)
  {
    rootIndex = root.key;
    max_v = count;
  }
 
  // Return the vector of nodes
  return combined;
}
 
// Driver Code
public static void main(String[] args)
{
  /*
              3
           /     \
          4       6
         /  \    /  \
       10    2  4    5
    */
 
  // Given Tree
  Node root = newNode(3);
  root.left = newNode(4);
  root.right = newNode(6);
  root.right.left = newNode(4);
  root.right.right = newNode(5);
  root.left.left = newNode(10);
  root.left.right = newNode(2);
 
  max_v = 0;
  rootIndex = -1;
 
  // Function Call
  findNodes(root);
 
  // Print the node value
  System.out.print(rootIndex);
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the above approach
 
# Stores the nodes to be deleted
max_v = 0
rootIndex  = 0
mp = {}
 
# Structure of a Tree node
class newNode:
     
    def __init__(self, key):
         
        self.key = key
        self.left = None
        self.right = None
 
# Function to compare the current node
# key with keys received from it left
# & right tree by Post Order traversal
def findNodes(root):
     
    global max_v
    global rootIndex
    global mp
     
    # Base Case
    if (root == None):
        return []
 
    # Find nodes lesser than the current
    # root in the left subtree
    left = findNodes(root.left)
 
    # Find nodes lesser than the current
    # root in the right subtree
    right = findNodes(root.right)
 
    # Stores all the nodes less than
    # the current node's
    combined = []
    count = 0
 
    # Add the nodes which are less
    # than current node in left[]
    for i in range(len(left)):
        if (left[i] < root.key):
            count += 1
             
        combined.append(left[i])
 
    # Add the nodes which are less
    # than current node in right[]
    for i in range(len(right)):
        if (right[i] < root.key):
            count += 1
             
        combined.append(right[i])
 
    # Create a combined vector for
    # pass to it's parent
    combined.append(root.key)
 
    # Stores key that has maximum nodes
    if (count > max_v):
        rootIndex = root.key
        max_v = count
 
    # Return the vector of nodes
    return combined
 
# Driver Code
if __name__ == '__main__':
     
    '''
               3
            /     \
           4       6
          / \     / \
        10   2   4   5
    '''
 
    # Given Tree
    root = None
    root = newNode(3)
    root.left = newNode(4)
    root.right = newNode(6)
    root.right.left = newNode(4)
    root.right.right = newNode(5)
    root.left.left = newNode(10)
    root.left.right = newNode(2)
 
    max_v = 0
    rootIndex = -1
 
    # Function Call
    findNodes(root)
 
    # Print the node value
    print(rootIndex)
 
# This code is contributed by ipg2016107


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Stores the nodes to be deleted
static Dictionary mp = new Dictionary();
static int max_v, rootIndex;
 
// Structure of a Tree node
class Node
{
    public int key;
    public Node left, right;
};
 
// Function to create a new node
static Node newNode(int key)
{
    Node temp = new Node();
    temp.key = key;
    temp.left = temp.right = null;
    return (temp);
}
 
// Function to compare the current node
// key with keys received from it left
// & right tree by Post Order traversal
static List findNodes(Node root)
{
     
    // Base Case
    if (root == null)
    {
        return new List();
    }
     
    // Find nodes lesser than the current
    // root in the left subtree
    List left = findNodes(root.left);
     
    // Find nodes lesser than the current
    // root in the right subtree
    List right = findNodes(root.right);
     
    // Stores all the nodes less than
    // the current node's
    List combined = new List();
    int count = 0;
     
    // Add the nodes which are less
    // than current node in []left
    for(int i = 0; i < left.Count; i++)
    {
        if (left[i] < root.key)
        {
            count += 1;
        }
        combined.Add(left[i]);
    }
     
    // Add the nodes which are less
    // than current node in []right
    for(int i = 0; i < right.Count; i++)
    {
        if (right[i] < root.key)
        {
            count += 1;
        }
        combined.Add(right[i]);
    }
     
    // Create a combined vector for
    // pass to it's parent
    combined.Add(root.key);
     
    // Stores key that has maximum nodes
    if (count > max_v)
    {
        rootIndex = root.key;
        max_v = count;
    }
     
    // Return the vector of nodes
    return combined;
}
 
// Driver Code
public static void Main(String[] args)
{
    /*
               3
            /     \
           4      6
          / \    / \
        10   2  4   5
        */
     
    // Given Tree
    Node root = newNode(3);
    root.left = newNode(4);
    root.right = newNode(6);
    root.right.left = newNode(4);
    root.right.right = newNode(5);
    root.left.left = newNode(10);
    root.left.right = newNode(2);
     
    max_v = 0;
    rootIndex = -1;
     
    // Function call
    findNodes(root);
     
    // Print the node value
    Console.Write(rootIndex);
}
}
 
// This code is contributed by Amit Katiyar


输出:
6




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

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