📜  检查完美二叉树的任何级别是否形成回文

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

检查完美二叉树的任何级别是否形成回文

给定一棵由N个节点组成的完美二叉树,任务是检查由树的任何级别中的节点形成的数字是否形成回文数。根节点被认为是回文
例子

方法:可以使用树上的广度优先搜索来解决该任务。请按照以下步骤解决问题:

  • 从根节点开始遍历树
  • 从下一层开始,保持该层所有节点串联形成的数量
  • 检查它是否是回文

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
struct Node {
    Node* left;
    Node* right;
    int hd;
    int data;
};
 
// Function to create a new node
Node* newNode(int key)
{
    Node* node = new Node();
    node->left = node->right = NULL;
    node->data = key;
    return node;
}
 
// Function to check if the number is
// palindrome or not
bool chkp(int n)
{
    string s = to_string(n);
    string k = s;
    reverse(s.begin(), s.end());
    if (k == s)
        return true;
    return false;
}
 
// Function to find whether any level
// forms a palindromic number
bool chklevel(Node* root)
{
 
    queue q;
    q.push(root);
    int k = 1;
    int p = k;
    int n = 0;
 
    // Using breadth-first-search(bfs)
    while (!q.empty()) {
 
        // if new level start
        if (p == 0) {
 
            // If not the first level
            if (k != 1)
 
                // Checking if the number
                // at current level
                // is palindrome
                if (chkp(n)) {
                    return true;
                }
 
            // Entering new level
            k *= 2;
            p = k;
            n = 0;
        }
 
        Node* t = q.front();
        q.pop();
        n = n * 10 + t->data;
        p--;
        if (t->left) {
            q.push(t->left);
        }
        if (t->right) {
            q.push(t->right);
        }
    }
 
    // If number at the last
    // level is palindrome
    if (chkp(n))
        return true;
    return false;
}
 
// Driver Code
int main()
{
    // Perfect Binary Tree formation
    Node* root = newNode(5);
    root->left = newNode(3);
    root->right = newNode(3);
    root->left->left = newNode(6);
    root->left->right = newNode(2);
    root->right->right = newNode(6);
    root->right->left = newNode(3);
    if (chklevel(root))
        cout << "Yes";
    else
        cout << "No";
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
  static class Node {
    Node left;
    Node right;
    int hd;
    int data;
  };
 
  // Function to create a new node
  static Node newNode(int key)
  {
    Node node = new Node();
    node.left = node.right = null;
    node.data = key;
    return node;
  }
  static String reverse(String input) {
    char[] a = input.toCharArray();
    int l, r = a.length - 1;
    for (l = 0; l < r; l++, r--) {
      char temp = a[l];
      a[l] = a[r];
      a[r] = temp;
    }
    return String.valueOf(a);
  }
  // Function to check if the number is
  // palindrome or not
  static boolean chkp(int n)
  {
    String s = String.valueOf(n);
    String k = s;
    s=reverse(s);
    if (k.equals(s))
      return true;
    return false;
  }
 
  // Function to find whether any level
  // forms a palindromic number
  static boolean chklevel(Node root)
  {
 
    Queue q = new LinkedList<>();
    q.add(root);
    int k = 1;
    int p = k;
    int n = 0;
 
    // Using breadth-first-search(bfs)
    while (!q.isEmpty()) {
 
      // if new level start
      if (p == 0) {
 
        // If not the first level
        if (k != 1)
 
          // Checking if the number
          // at current level
          // is palindrome
          if (chkp(n)) {
            return true;
          }
 
        // Entering new level
        k *= 2;
        p = k;
        n = 0;
      }
 
      Node t = q.peek();
      q.remove();
      n = n * 10 + t.data;
      p--;
      if (t.left!=null) {
        q.add(t.left);
      }
      if (t.right!=null) {
        q.add(t.right);
      }
    }
 
    // If number at the last
    // level is palindrome
    if (chkp(n))
      return true;
    return false;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
     
    // Perfect Binary Tree formation
    Node root = newNode(5);
    root.left = newNode(3);
    root.right = newNode(3);
    root.left.left = newNode(6);
    root.left.right = newNode(2);
    root.right.right = newNode(6);
    root.right.left = newNode(3);
    if (chklevel(root))
      System.out.print("Yes");
    else
      System.out.print("No");
  }
}
 
// This code is contributed by shikhasingrajput


Python3
# Python code for the above approach
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.hd = 0
        self.data = key
 
# Function to create a  node
 
# Function to check if the number is
# palindrome or not
def chkp(n):
    s = str(n)
    k = s[::-1]
 
    if (k == s):
        return True
    return False
 
# Function to find whether any level
# forms a palindromic number
def chklevel(root):
 
    q = []
    q.append(root)
    k = 1
    p = k
    n = 0
 
    # Using breadth-first-search(bfs)
    while (len(q) != 0):
 
        # if new level start
        if (p == 0):
 
            # If not the first level
            if (k != 1):
 
                # Checking if the number
                # at current level
                # is palindrome
                if (chkp(n)):
                    return True
 
            # Entering new level
            k *= 2
            p = k
            n = 0
 
        t = q[0]
        q.pop(0)
        n = n * 10 + t.data
        p -= 1
        if (t.left != None):
            q.append(t.left)
 
        if (t.right != None):
            q.append(t.right)
 
    # If number at the last
    # level is palindrome
    if (chkp(n)):
        return True
    return False
 
# Driver Code
 
# Perfect Binary Tree formation
root = Node(5)
root.left = Node(3)
root.right = Node(3)
root.left.left = Node(6)
root.left.right = Node(2)
root.right.right = Node(6)
root.right.left = Node(3)
if (chklevel(root)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by Saurabh Jaiswal


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  class Node {
    public Node left;
    public Node right;
    public int hd;
    public int data;
  };
 
  // Function to create a new node
  static Node newNode(int key)
  {
    Node node = new Node();
    node.left = node.right = null;
    node.data = key;
    return node;
  }
  static String reverse(String input) {
    char[] a = input.ToCharArray();
    int l, r = a.Length - 1;
    for (l = 0; l < r; l++, r--) {
      char temp = a[l];
      a[l] = a[r];
      a[r] = temp;
    }
    return String.Join("",a);
  }
   
  // Function to check if the number is
  // palindrome or not
  static bool chkp(int n)
  {
    String s = String.Join("",n);
    String k = s;
    s=reverse(s);
    if (k.Equals(s))
      return true;
    return false;
  }
 
  // Function to find whether any level
  // forms a palindromic number
  static bool chklevel(Node root)
  {
 
    Queue q = new Queue();
    q.Enqueue(root);
    int k = 1;
    int p = k;
    int n = 0;
 
    // Using breadth-first-search(bfs)
    while (q.Count!=0) {
 
      // if new level start
      if (p == 0) {
 
        // If not the first level
        if (k != 1)
 
          // Checking if the number
          // at current level
          // is palindrome
          if (chkp(n)) {
            return true;
          }
 
        // Entering new level
        k *= 2;
        p = k;
        n = 0;
      }
 
      Node t = q.Peek();
      q.Dequeue();
      n = n * 10 + t.data;
      p--;
      if (t.left!=null) {
        q.Enqueue(t.left);
      }
      if (t.right!=null) {
        q.Enqueue(t.right);
      }
    }
 
    // If number at the last
    // level is palindrome
    if (chkp(n))
      return true;
    return false;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
     
    // Perfect Binary Tree formation
    Node root = newNode(5);
    root.left = newNode(3);
    root.right = newNode(3);
    root.left.left = newNode(6);
    root.left.right = newNode(2);
    root.right.right = newNode(6);
    root.right.left = newNode(3);
    if (chklevel(root))
      Console.Write("Yes");
    else
      Console.Write("No");
  }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出
Yes

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