检查给定的通用 N 元树是否水平对称
给定一个 N 叉树根,任务是检查它是否水平对称(自身的镜像)。
例子:
Input: root = 7
/ / \ \
4 2 2 4
/ | / | | \ | \
3 2 6 7 7 6 2 3
Output: true
Explanation: The left side of the tree is a mirror image of the right side
Input: root= 2
/ | \
3 4 3
/ | \
5 6 5
Output: true
方法:给定的问题可以通过使用前序遍历来解决。这个想法是传递两个根节点作为参数,并检查当前节点的值是否相同,并使用递归来检查左节点的子节点的值是否与右节点的子节点的值相同。
可以按照以下步骤解决问题:
- 在 N 叉树上应用前序遍历:
- 检查两个根节点的值是否相同。
- 另外,检查两个根的节点数是否相同
- 从左到右迭代左根的子节点,同时从右到左迭代右节点的节点并使用递归。
下面是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
class Node
{
public:
vector children;
int val;
// constructor
Node(int v)
{
val = v;
children = {};
}
};
// Preorder traversal to check
// if the generic tree
// is symmetric or not
bool preorder(
Node *root1, Node *root2)
{
// If the values of both the
// root is not the same or if
// the number of children are
// not the same then return false
if (root1->val != root2->val || root1->children.size() != root2->children.size())
return false;
// Number of children
int size = root1->children.size();
// Iterate left to right on
// left root and right to left
// on the right root
for (int i = 0; i < (size+1)/2; i++)
{
// If any one branch is not
// symmetric then return false
if (!preorder(
root1->children[i],
root2->children[size - 1 - i]))
return false;
}
// Tree is symmetric return true
return true;
}
// Function to check if the generic
// tree is symmetric or not
bool isSymmetric(Node *root)
{
// Base case
if (root == NULL)
return true;
// Apply preorder traversal
// on the tree
return preorder(root, root);
}
// Driver code
int main()
{
// Initialize the tree
Node *seven = new Node(7);
Node *five1 = new Node(5);
Node *five2 = new Node(5);
Node *four = new Node(4);
seven->children.push_back(five1);
seven->children.push_back(four);
seven->children.push_back(five2);
// Call the function
// and print the result
if (isSymmetric(seven))
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
return 0;
}
// This code is contributed by Potta Lokesh
Java
// Java implementation for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to check if the generic
// tree is symmetric or not
public static boolean isSymmetric(Node root)
{
// Base case
if (root == null)
return true;
// Apply preorder traversal
// on the tree
return preorder(root, root);
}
// Preorder traversal to check
// if the generic tree
// is symmetric or not
public static boolean preorder(
Node root1, Node root2)
{
// If the values of both the
// root is not the same or if
// the number of children are
// not the same then return false
if (root1.val != root2.val
|| root1.children.size()
!= root2.children.size())
return false;
// Number of children
int size = root1.children.size();
// Iterate left to right on
// left root and right to left
// on the right root
for (int i = 0; i < size; i++) {
// If any one branch is not
// symmetric then return false
if (!preorder(
root1.children.get(i),
root2.children.get(size - 1 - i)))
return false;
}
// Tree is symmetric return true
return true;
}
// Driver code
public static void main(String[] args)
{
// Initialize the tree
Node seven = new Node(7);
Node five1 = new Node(5);
Node five2 = new Node(5);
Node four = new Node(4);
seven.children.add(five1);
seven.children.add(four);
seven.children.add(five2);
// Call the function
// and print the result
System.out.println(
isSymmetric(seven));
}
static class Node {
List children;
int val;
// constructor
public Node(int val)
{
this.val = val;
children = new ArrayList<>();
}
}
}
Python3
# Python code for the above approach
class Node:
def __init__(self, val):
self.val = val
self.children = []
# Preorder traversal to check
# if the generic tree
# is symmetric or not
def preorder(root1, root2):
# If the values of both the
# root is not the same or if
# the number of children are
# not the same then return false
if (root1.val != root2.val or len(root1.children) != len(root2.children)):
return False
# Number of children
size = len(root1.children)
# Iterate left to right on
# left root and right to left
# on the right root
for i in range(0, (size + 1)//2):
# If any one branch is not
# symmetric then return false
if (preorder(root1.children[i],
root2.children[size - 1 - i]) == False):
return False
# Tree is symmetric return true
return True
# Function to check if the generic
# tree is symmetric or not
def isSymmetric(root):
# Base case
if (root == None):
return True
# Apply preorder traversal
# on the tree
return preorder(root, root)
# Driver code
# Initialize the tree
seven = Node(7)
five1 = Node(5)
five2 = Node(5)
four = Node(4)
seven.children.append(five1)
seven.children.append(four)
seven.children.append(five2)
# Call the function
# and print the result
if (isSymmetric(seven)):
print("True")
else:
print("False")
# This code is contributed by rj13to.
C#
// C# implementation for the above approach
using System;
using System.Collections.Generic;
public class GFG {
// Function to check if the generic
// tree is symmetric or not
static bool isSymmetric(Node root)
{
// Base case
if (root == null)
return true;
// Apply preorder traversal
// on the tree
return preorder(root, root);
}
// Preorder traversal to check
// if the generic tree
// is symmetric or not
static bool preorder(
Node root1, Node root2)
{
// If the values of both the
// root is not the same or if
// the number of children are
// not the same then return false
if (root1.val != root2.val
|| root1.children.Count
!= root2.children.Count)
return false;
// Number of children
int size = root1.children.Count;
// Iterate left to right on
// left root and right to left
// on the right root
for (int i = 0; i < size; i++) {
// If any one branch is not
// symmetric then return false
if (!preorder(
root1.children[i],
root2.children[size - 1 - i]))
return false;
}
// Tree is symmetric return true
return true;
}
// Driver code
public static void Main(String[] args)
{
// Initialize the tree
Node seven = new Node(7);
Node five1 = new Node(5);
Node five2 = new Node(5);
Node four = new Node(4);
seven.children.Add(five1);
seven.children.Add(four);
seven.children.Add(five2);
// Call the function
// and print the result
Console.WriteLine(
isSymmetric(seven));
}
class Node {
public List children;
public int val;
// constructor
public Node(int val)
{
this.val = val;
children = new List();
}
}
}
// This code is contributed by shikhasingrajput
Javascript
true
时间复杂度: O(N),其中 N 是树中的节点数
辅助空间: O(H),其中H是树的高度