📌  相关文章
📜  在给定的二叉树中查找给定节点的级别位置

📅  最后修改于: 2022-05-13 01:56:08.132000             🧑  作者: Mango

在给定的二叉树中查找给定节点的级别位置

给定一棵二叉树和一个整数X,任务是找出给定树中所有出现的X ,并打印它的级别及其在该级别上从左到右的位置。如果未找到X ,则打印 -1。

例子:

方法这个问题可以通过使用队列的二叉树的级别顺序遍历来解决。

  • 使用队列执行给定二叉树的级别顺序遍历。
  • 在遍历过程中从左到右跟踪级别数和节点数
  • 每当在遍历过程中遇到 X 时,打印或存储 X 当前出现的级别计数和位置。

下面是上述方法的实现:

C++
// C++ program to print level and
// position of Node X in binary tree
 
#include 
using namespace std;
 
// A Binary Tree Node
struct Node {
    int data;
    struct Node *left, *right;
};
 
// Function to find and print
// level and position of node X
void printLevelandPosition(Node* root, int X)
{
    // Base Case
    if (root == NULL)
        return;
 
    // Create an empty queue
    queue q;
 
    // Enqueue Root and initialize height
    q.push(root);
 
    // Create and initialize current
    // level and position by 1
    int currLevel = 1, position = 1;
 
    while (q.empty() == false) {
 
        int size = q.size();
 
        while (size--) {
 
            Node* node = q.front();
 
            // print if node data equal to X
            if (node->data == X)
                cout << "(" << currLevel
                     << " " << position
                     << "), ";
            q.pop();
 
            // increment the position
            position++;
 
            // Enqueue left child
            if (node->left != NULL)
                q.push(node->left);
 
            // Enqueue right child
            if (node->right != NULL)
                q.push(node->right);
        }
        // increment the level
        currLevel++;
        position = 1;
    }
}
 
// Utility function to create a new tree node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Driver program to test above functions
int main()
{
    // Let us create binary tree
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(2);
 
    int X = 2;
 
    printLevelandPosition(root, X);
    return 0;
}


Java
// JAVA program to print level and
// position of Node X in binary tree
import java.util.*;
 
// A Binary Tree Node
class Node {
  int data;
  Node left;
  Node right;
}
class GFG
{
 
  // Function to find and print
  // level and position of node X
  public static void printLevelandPosition(Node root,
                                           int X)
  {
    // Base Case
    if (root == null)
      return;
 
    // Create an empty queue
    Queue q = new LinkedList<>();
 
    // Enqueue Root and initialize height
    q.add(root);
 
    // Create and initialize current
    // level and position by 1
    int currLevel = 1, position = 1;
 
    while (q.size() != 0) {
 
      int size = q.size();
 
      while ((size--) != 0) {
 
        Node node = q.peek();
 
        // print if node data equal to X
        if (node.data == X)
          System.out.print("(" + currLevel + " "
                           + position + "), ");
        q.remove();
 
        // increment the position
        position++;
 
        // Enqueue left child
        if (node.left != null)
          q.add(node.left);
 
        // Enqueue right child
        if (node.right != null)
          q.add(node.right);
      }
      // increment the level
      currLevel++;
      position = 1;
    }
  }
 
  // Utility function to create a new tree node
  public static Node newNode(int data)
  {
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
  }
 
  // Driver program to test above functions
  public static void main(String[] args)
  {
    // Let us create binary tree
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(2);
 
    int X = 2;
 
    printLevelandPosition(root, X);
  }
}
 
// This code is contributed by Taranpreet


Python3
# Python code for the above approach
class Node:
    def __init__(self,d):
        self.data = d
        self.left = None
        self.right = None
     
# Function to find and print
# level and position of node X
def printLevelandPosition(root, X):
 
    # Base Case
    if (root == None):
        return
 
    # Create an empty queue
    q = []
 
    # Enqueue Root and initialize height
    q.append(root)
 
    # Create and initialize current
    # level and position by 1
    currLevel,position = 1,1
 
    while (len(q) != 0):
 
        size = len(q)
 
        while (size != 0):
 
            node = q[0]
            q = q[1:]
 
            # print if node data equal to X
            if (node.data == X):
                print (f"({currLevel} {position}),",end =" ")
         
 
            # increment the position
            position += 1
 
            # Enqueue left child
            if (node.left != None):
                q.append(node.left)
 
            # Enqueue right child
            if (node.right != None):
                q.append(node.right)
             
            size -= 1
 
        # increment the level
        currLevel += 1
        position = 1
 
# Driver program to test above functions
 
# Let us create binary tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(2)
 
X = 2
 
printLevelandPosition(root, X)
 
# This code is contributed by shinjanpatra


C#
// C# program to print level and
// position of Node X in binary tree
using System;
using System.Collections.Generic;
 
 
// A Binary Tree Node
public class Node {
  public int data;
  public Node left;
  public Node right;
}
 
public class GFG {
 
  // Function to find and print
  // level and position of node X
  public static void printLevelandPosition(Node root, int X) {
    // Base Case
    if (root == null)
      return;
 
    // Create an empty queue
    Queue q = new Queue();
 
    // Enqueue Root and initialize height
    q.Enqueue(root);
 
    // Create and initialize current
    // level and position by 1
    int currLevel = 1, position = 1;
 
    while (q.Count != 0) {
 
      int size = q.Count;
 
      while ((size--) != 0) {
 
        Node node = q.Peek();
 
        // print if node data equal to X
        if (node.data == X)
          Console.Write("(" + currLevel + " " + position + "), ");
        q.Dequeue();
 
        // increment the position
        position++;
 
        // Enqueue left child
        if (node.left != null)
          q.Enqueue(node.left);
 
        // Enqueue right child
        if (node.right != null)
          q.Enqueue(node.right);
      }
      // increment the level
      currLevel++;
      position = 1;
    }
  }
 
  // Utility function to create a new tree node
  public static Node newNode(int data) {
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
  }
 
  // Driver program to test above functions
  public static void Main(String[] args) {
    // Let us create binary tree
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(2);
 
    int X = 2;
 
    printLevelandPosition(root, X);
  }
}
 
// This code is contributed by Rajput-Ji


Javascript



输出
(2 1), (3 2), 

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