可折叠二叉树
问题:给定一棵二叉树,找出这棵树是否可以折叠。
如果树的左右子树在结构上互为镜像,则可以折叠树。一棵空树被认为是可折叠的。
Consider the below trees:
(a) and (b) can be folded.
(c) and (d) cannot be folded.
(a)
10
/ \
7 15
\ /
9 11
(b)
10
/ \
7 15
/ \
9 11
(c)
10
/ \
7 15
/ /
5 11
(d)
10
/ \
7 15
/ \ /
9 10 12
方法1(将左子树更改为其镜像并与右子树进行比较)
算法:isFoldable(root)
1) If tree is empty, then return true.
2) Convert the left subtree to its mirror image
mirror(root->left); /* See this post */
3) Check if the structure of left subtree and right subtree is same
and store the result.
res = isStructSame(root->left, root->right); /*isStructSame()
recursively compares structures of two subtrees and returns
true if structures are same */
4) Revert the changes made in step (2) to get the original tree.
mirror(root->left);
5) Return result res stored in step 2.
感谢 ajaym 提出这种方法。
C++
// C++ program to check foldable binary tree
#include
using namespace std;
/* You would want to remove below
3 lines if your compiler supports
bool, true and false */
#define bool int
#define true 1
#define false 0
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
class node {
public:
int data;
node* left;
node* right;
};
/* converts a tree to its mirror image */
void mirror(node* node);
/* returns true if structure of
two trees a and b is same only
structure is considered for comparison, not data! */
bool isStructSame(node* a, node* b);
/* Returns true if the given tree is foldable */
bool isFoldable(node* root)
{
bool res;
/* base case */
if (root == NULL)
return true;
/* convert left subtree to its mirror */
mirror(root->left);
/* Compare the structures of the
right subtree and mirrored
left subtree */
res = isStructSame(root->left, root->right);
/* Get the original tree back */
mirror(root->left);
return res;
}
bool isStructSame(node* a, node* b)
{
if (a == NULL && b == NULL) {
return true;
}
if (a != NULL && b != NULL && isStructSame(a->left, b->left) && isStructSame(a->right, b->right)) {
return true;
}
return false;
}
/* UTILITY FUNCTIONS */
/* Change a tree so that the roles of the left and
right pointers are swapped at every node.
See https:// www.geeksforgeeks.org/?p=662 for details */
void mirror(node* Node)
{
if (Node == NULL)
return;
else {
node* temp;
/* do the subtrees */
mirror(Node->left);
mirror(Node->right);
/* swap the pointers in this node */
temp = Node->left;
Node->left = Node->right;
Node->right = temp;
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
/* Driver program to test mirror() */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->right->left = newNode(4);
root->left->right = newNode(5);
if (isFoldable(root) == 1) {
cout << "tree is foldable";
}
else {
cout << "\ntree is not foldable";
}
return 0;
}
// This code is contributed by rathbhupendra
C
#include
#include
/* You would want to remove below 3 lines if your compiler
supports bool, true and false */
#define bool int
#define true 1
#define false 0
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node {
int data;
struct node* left;
struct node* right;
};
/* converts a tree to its mirror image */
void mirror(struct node* node);
/* returns true if structure of two trees a and b is same
Only structure is considered for comparison, not data! */
bool isStructSame(struct node* a, struct node* b);
/* Returns true if the given tree is foldable */
bool isFoldable(struct node* root)
{
bool res;
/* base case */
if (root == NULL)
return true;
/* convert left subtree to its mirror */
mirror(root->left);
/* Compare the structures of the right subtree and mirrored
left subtree */
res = isStructSame(root->left, root->right);
/* Get the original tree back */
mirror(root->left);
return res;
}
bool isStructSame(struct node* a, struct node* b)
{
if (a == NULL && b == NULL) {
return true;
}
if (a != NULL && b != NULL && isStructSame(a->left, b->left) && isStructSame(a->right, b->right)) {
return true;
}
return false;
}
/* UTILITY FUNCTIONS */
/* Change a tree so that the roles of the left and
right pointers are swapped at every node.
See https:// www.geeksforgeeks.org/?p=662 for details */
void mirror(struct node* node)
{
if (node == NULL)
return;
else {
struct node* temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
/* Driver program to test mirror() */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->right->left = newNode(4);
root->left->right = newNode(5);
if (isFoldable(root) == 1) {
printf("\n tree is foldable");
}
else {
printf("\n tree is not foldable");
}
getchar();
return 0;
}
Java
// Java program to check foldable binary tree
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node {
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
/* Returns true if the given tree is foldable */
boolean isFoldable(Node node)
{
boolean res;
/* base case */
if (node == null)
return true;
/* convert left subtree to its mirror */
mirror(node.left);
/* Compare the structures of the right subtree and mirrored
left subtree */
res = isStructSame(node.left, node.right);
/* Get the original tree back */
mirror(node.left);
return res;
}
boolean isStructSame(Node a, Node b)
{
if (a == null && b == null)
return true;
if (a != null && b != null
&& isStructSame(a.left, b.left)
&& isStructSame(a.right, b.right))
return true;
return false;
}
/* UTILITY FUNCTIONS */
/* Change a tree so that the roles of the left and
right pointers are swapped at every node.
See https:// www.geeksforgeeks.org/?p=662 for details */
void mirror(Node node)
{
if (node == null)
return;
else {
Node temp;
/* do the subtrees */
mirror(node.left);
mirror(node.right);
/* swap the pointers in this node */
temp = node.left;
node.left = node.right;
node.right = temp;
}
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
if (tree.isFoldable(tree.root))
System.out.println("tree is foldable");
else
System.out.println("Tree is not foldable");
}
}
// This code has been contributed by Mayank Jaiswal
C#
// C# program to check foldable
// binary tree
using System;
/* A binary tree node has data,
pointer to left child and
a pointer to right child */
class Node {
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
/* Returns true if the given
tree is foldable */
Boolean isFoldable(Node node)
{
Boolean res;
/* base case */
if (node == null)
return true;
/* convert left subtree
to its mirror */
mirror(node.left);
/* Compare the structures of the
right subtree and mirrored
left subtree */
res = isStructSame(node.left, node.right);
/* Get the original tree back */
mirror(node.left);
return res;
}
Boolean isStructSame(Node a, Node b)
{
if (a == null && b == null)
return true;
if (a != null && b != null && isStructSame(a.left, b.left) && isStructSame(a.right, b.right))
return true;
return false;
}
/* UTILITY FUNCTIONS */
/* Change a tree so that the roles
of the left and right pointers are
swapped at every node.
See https:// www.geeksforgeeks.org/?p=662
for details */
void mirror(Node node)
{
if (node == null)
return;
else {
Node temp;
/* do the subtrees */
mirror(node.left);
mirror(node.right);
/* swap the pointers in this node */
temp = node.left;
node.left = node.right;
node.right = temp;
}
}
// Driver Code
static public void Main(String[] args)
{
BinaryTree tree = new BinaryTree();
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
if (tree.isFoldable(tree.root))
Console.WriteLine("tree is foldable");
else
Console.WriteLine("Tree is not foldable");
}
}
// This code is contributed by Arnab Kundu
Javascript
C++
#include
using namespace std;
/* You would want to remove below 3 lines if your compiler
supports bool, true and false */
#define bool int
#define true 1
#define false 0
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class node {
public:
int data;
node* left;
node* right;
};
/* A utility function that checks
if trees with roots as n1 and n2
are mirror of each other */
bool IsFoldableUtil(node* n1, node* n2);
/* Returns true if the given tree can be folded */
bool IsFoldable(node* root)
{
if (root == NULL) {
return true;
}
return IsFoldableUtil(root->left, root->right);
}
/* A utility function that checks
if trees with roots as n1 and n2
are mirror of each other */
bool IsFoldableUtil(node* n1, node* n2)
{
/* If both left and right subtrees are NULL,
then return true */
if (n1 == NULL && n2 == NULL) {
return true;
}
/* If one of the trees is NULL and other is not,
then return false */
if (n1 == NULL || n2 == NULL) {
return false;
}
/* Otherwise check if left and right subtrees are
mirrors of their counterparts */
return IsFoldableUtil(n1->left, n2->right)
&& IsFoldableUtil(n1->right, n2->left);
}
/*UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
/* Driver code */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
if (IsFoldable(root) == true) {
cout << "Tree is foldable";
}
else {
cout << "Tree is not foldable";
}
return 0;
}
// This is code is contributed by rathbhupendra
C
#include
#include
/* You would want to remove below 3 lines if your compiler
supports bool, true and false */
#define bool int
#define true 1
#define false 0
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node {
int data;
struct node* left;
struct node* right;
};
/* A utility function that checks if trees with roots as n1
and n2 are mirror of each other */
bool IsFoldableUtil(struct node* n1, struct node* n2);
/* Returns true if the given tree can be folded */
bool IsFoldable(struct node* root)
{
if (root == NULL) {
return true;
}
return IsFoldableUtil(root->left, root->right);
}
/* A utility function that checks if trees with roots as n1
and n2 are mirror of each other */
bool IsFoldableUtil(struct node* n1, struct node* n2)
{
/* If both left and right subtrees are NULL,
then return true */
if (n1 == NULL && n2 == NULL) {
return true;
}
/* If one of the trees is NULL and other is not,
then return false */
if (n1 == NULL || n2 == NULL) {
return false;
}
/* Otherwise check if left and right subtrees are
mirrors of their counterparts */
return IsFoldableUtil(n1->left, n2->right)
&& IsFoldableUtil(n1->right, n2->left);
}
/*UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node
= (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
/* Driver program to test mirror() */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
if (IsFoldable(root) == true) {
printf("\n tree is foldable");
}
else {
printf("\n tree is not foldable");
}
getchar();
return 0;
}
Java
// Java program to check foldable binary tree
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node {
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
/* Returns true if the given tree can be folded */
boolean IsFoldable(Node node)
{
if (node == null)
return true;
return IsFoldableUtil(node.left, node.right);
}
/* A utility function that checks if trees with roots as
n1 and n2 are mirror of each other */
boolean IsFoldableUtil(Node n1, Node n2)
{
/* If both left and right subtrees are NULL,
then return true */
if (n1 == null && n2 == null)
return true;
/* If one of the trees is NULL and other is not,
then return false */
if (n1 == null || n2 == null)
return false;
/* Otherwise check if left and right subtrees are
mirrors of their counterparts */
return IsFoldableUtil(n1.left, n2.right)
&& IsFoldableUtil(n1.right, n2.left);
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
if (tree.IsFoldable(tree.root))
System.out.println("tree is foldable");
else
System.out.println("Tree is not foldable");
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Python3 program to check
# foldable binary tree
# Utility function to create a new
# tree node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Returns true if the given tree can be folded
def IsFoldable(root):
if (root == None):
return True
return IsFoldableUtil(root.left, root.right)
# A utility function that checks
# if trees with roots as n1 and n2
# are mirror of each other
def IsFoldableUtil(n1, n2):
# If both left and right subtrees are NULL,
# then return true
if n1 == None and n2 == None:
return True
# If one of the trees is NULL and other is not,
# then return false
if n1 == None or n2 == None:
return False
# Otherwise check if left and
# right subtrees are mirrors of
# their counterparts
d1 = IsFoldableUtil(n1.left, n2.right)
d2 = IsFoldableUtil(n1.right, n2.left)
return d1 and d2
# Driver code
if __name__ == "__main__":
""" The constructed binary tree is
1
/ \
2 3
\ /
4 5
"""
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.right = newNode(4)
root.right.left = newNode(5)
if IsFoldable(root):
print("Tree is foldable")
else:
print("Tree is not foldable")
# This code is contributed by
# Anupam Baranwal(anupambaranwal)
C#
// C# program to check foldable binary tree
using System;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
public class Node {
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree {
Node root;
/* Returns true if the given tree can be folded */
bool IsFoldable(Node node)
{
if (node == null)
return true;
return IsFoldableUtil(node.left, node.right);
}
/* A utility function that checks if
trees with roots as n1 and n2
are mirror of each other */
bool IsFoldableUtil(Node n1, Node n2)
{
/* If both left and right subtrees are NULL,
then return true */
if (n1 == null && n2 == null)
return true;
/* If one of the trees is NULL and other is not,
then return false */
if (n1 == null || n2 == null)
return false;
/* Otherwise check if left and right subtrees are
mirrors of their counterparts */
return IsFoldableUtil(n1.left, n2.right)
&& IsFoldableUtil(n1.right, n2.left);
}
/* Driver code */
public static void Main(String[] args)
{
BinaryTree tree = new BinaryTree();
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
if (tree.IsFoldable(tree.root))
Console.WriteLine("tree is foldable");
else
Console.WriteLine("Tree is not foldable");
}
}
/* This code contributed by PrinciRaj1992 */
Javascript
Java
// Java code for the above approach
import java.util.Queue;
import java.util.LinkedList;
public class FoldableTrees {
Node root = null;
// Class Node to store the data and left and right pointers
class Node {
int key;
Node left;
Node right;
Node(int key) {
this.key = key;
left = right = null;
}
}
// Function to find whether the tree is foldable
boolean isFoldable() {
// Queue to store visited nodes
Queue q = new LinkedList<>();
// Initially add the left and right nodes of root
if (root != null) {
q.add(root.left);
q.add(root.right);
}
while (!q.isEmpty()) {
// Remove the front 2 nodes to
// check for null condition
Node p = q.remove();
Node r = q.remove();
// If both are null, continue and check
// the further elements
if (p == null && r == null)
continue;
// If one of them is not null, then return false
if ((p == null && r != null) || (p != null && r == null))
return false;
/* Insert in the same order:
1. left of left subtree
2. right of right subtree
3.right of left subtree
4.left of right subtree */
q.add(p.left);
q.add(r.right);
q.add(p.right);
q.add(r.left);
}
// Only if the tree is foldable
return true;
}
// Driver code
public static void main(String args[]) {
FoldableTrees tree = new FoldableTrees();
// Insert data into the tree
tree.root = tree.new Node(1);
tree.root.left = tree.new Node(2);
tree.root.right = tree.new Node(3);
tree.root.right.left = tree.new Node(4);
tree.root.left.right = tree.new Node(5);
// Function call
if(tree.isFoldable())
System.out.println("Tree is foldable");
else
System.out.println("Tree is not foldable");
}
}
//This method is contributed by likhita AVL
C#
using System;
using System.Collections.Generic;
public class Node
{
public int key;
public Node left,right;
public Node(int key)
{
this.key=key;
this.left=this.right=null;
}
}
public class FoldableTrees
{
Node root = null;
// Function to find whether the tree is foldable
bool isFoldable() {
// Queue to store visited nodes
Queue q = new Queue();
// Initially add the left and right nodes of root
if (root != null) {
q.Enqueue(root.left);
q.Enqueue(root.right);
}
while (q.Count!=0) {
// Remove the front 2 nodes to
// check for null condition
Node p = q.Dequeue();
Node r = q.Dequeue();
// If both are null, continue and check
// the further elements
if (p == null && r == null)
continue;
// If one of them is not null, then return false
if ((p == null && r != null) || (p != null && r == null))
return false;
/* Insert in the same order:
1. left of left subtree
2. right of right subtree
3.right of left subtree
4.left of right subtree */
q.Enqueue(p.left);
q.Enqueue(r.right);
q.Enqueue(p.right);
q.Enqueue(r.left);
}
// Only if the tree is foldable
return true;
}
// Driver code
static public void Main ()
{
FoldableTrees tree = new FoldableTrees();
// Insert data into the tree
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
// Function call
if(tree.isFoldable())
Console.WriteLine("Tree is foldable");
else
Console.WriteLine("Tree is not foldable");
}
}
// This code is contributed by patel2127.
Javascript
输出
tree is foldable
时间复杂度: O(n)
方法二(检查左右子树是否镜像)
主要有两个功能:
// 检查树是否可以折叠
IsFoldable(root)
1) If tree is empty then return true
2) Else check if left and right subtrees are structure wise mirrors of
each other. Use utility function IsFoldableUtil(root->left,
root->right) for this.
// 检查 n1 和 n2 是否互为镜像。
IsFoldableUtil(n1, n2)
1) If both trees are empty then return true.
2) If one of them is empty and other is not then return false.
3) Return true if following conditions are met
a) n1->left is mirror of n2->right
b) n1->right is mirror of n2->left
C++
#include
using namespace std;
/* You would want to remove below 3 lines if your compiler
supports bool, true and false */
#define bool int
#define true 1
#define false 0
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class node {
public:
int data;
node* left;
node* right;
};
/* A utility function that checks
if trees with roots as n1 and n2
are mirror of each other */
bool IsFoldableUtil(node* n1, node* n2);
/* Returns true if the given tree can be folded */
bool IsFoldable(node* root)
{
if (root == NULL) {
return true;
}
return IsFoldableUtil(root->left, root->right);
}
/* A utility function that checks
if trees with roots as n1 and n2
are mirror of each other */
bool IsFoldableUtil(node* n1, node* n2)
{
/* If both left and right subtrees are NULL,
then return true */
if (n1 == NULL && n2 == NULL) {
return true;
}
/* If one of the trees is NULL and other is not,
then return false */
if (n1 == NULL || n2 == NULL) {
return false;
}
/* Otherwise check if left and right subtrees are
mirrors of their counterparts */
return IsFoldableUtil(n1->left, n2->right)
&& IsFoldableUtil(n1->right, n2->left);
}
/*UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
/* Driver code */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
if (IsFoldable(root) == true) {
cout << "Tree is foldable";
}
else {
cout << "Tree is not foldable";
}
return 0;
}
// This is code is contributed by rathbhupendra
C
#include
#include
/* You would want to remove below 3 lines if your compiler
supports bool, true and false */
#define bool int
#define true 1
#define false 0
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node {
int data;
struct node* left;
struct node* right;
};
/* A utility function that checks if trees with roots as n1
and n2 are mirror of each other */
bool IsFoldableUtil(struct node* n1, struct node* n2);
/* Returns true if the given tree can be folded */
bool IsFoldable(struct node* root)
{
if (root == NULL) {
return true;
}
return IsFoldableUtil(root->left, root->right);
}
/* A utility function that checks if trees with roots as n1
and n2 are mirror of each other */
bool IsFoldableUtil(struct node* n1, struct node* n2)
{
/* If both left and right subtrees are NULL,
then return true */
if (n1 == NULL && n2 == NULL) {
return true;
}
/* If one of the trees is NULL and other is not,
then return false */
if (n1 == NULL || n2 == NULL) {
return false;
}
/* Otherwise check if left and right subtrees are
mirrors of their counterparts */
return IsFoldableUtil(n1->left, n2->right)
&& IsFoldableUtil(n1->right, n2->left);
}
/*UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node
= (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
/* Driver program to test mirror() */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
if (IsFoldable(root) == true) {
printf("\n tree is foldable");
}
else {
printf("\n tree is not foldable");
}
getchar();
return 0;
}
Java
// Java program to check foldable binary tree
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node {
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
/* Returns true if the given tree can be folded */
boolean IsFoldable(Node node)
{
if (node == null)
return true;
return IsFoldableUtil(node.left, node.right);
}
/* A utility function that checks if trees with roots as
n1 and n2 are mirror of each other */
boolean IsFoldableUtil(Node n1, Node n2)
{
/* If both left and right subtrees are NULL,
then return true */
if (n1 == null && n2 == null)
return true;
/* If one of the trees is NULL and other is not,
then return false */
if (n1 == null || n2 == null)
return false;
/* Otherwise check if left and right subtrees are
mirrors of their counterparts */
return IsFoldableUtil(n1.left, n2.right)
&& IsFoldableUtil(n1.right, n2.left);
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
if (tree.IsFoldable(tree.root))
System.out.println("tree is foldable");
else
System.out.println("Tree is not foldable");
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Python3 program to check
# foldable binary tree
# Utility function to create a new
# tree node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Returns true if the given tree can be folded
def IsFoldable(root):
if (root == None):
return True
return IsFoldableUtil(root.left, root.right)
# A utility function that checks
# if trees with roots as n1 and n2
# are mirror of each other
def IsFoldableUtil(n1, n2):
# If both left and right subtrees are NULL,
# then return true
if n1 == None and n2 == None:
return True
# If one of the trees is NULL and other is not,
# then return false
if n1 == None or n2 == None:
return False
# Otherwise check if left and
# right subtrees are mirrors of
# their counterparts
d1 = IsFoldableUtil(n1.left, n2.right)
d2 = IsFoldableUtil(n1.right, n2.left)
return d1 and d2
# Driver code
if __name__ == "__main__":
""" The constructed binary tree is
1
/ \
2 3
\ /
4 5
"""
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.right = newNode(4)
root.right.left = newNode(5)
if IsFoldable(root):
print("Tree is foldable")
else:
print("Tree is not foldable")
# This code is contributed by
# Anupam Baranwal(anupambaranwal)
C#
// C# program to check foldable binary tree
using System;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
public class Node {
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree {
Node root;
/* Returns true if the given tree can be folded */
bool IsFoldable(Node node)
{
if (node == null)
return true;
return IsFoldableUtil(node.left, node.right);
}
/* A utility function that checks if
trees with roots as n1 and n2
are mirror of each other */
bool IsFoldableUtil(Node n1, Node n2)
{
/* If both left and right subtrees are NULL,
then return true */
if (n1 == null && n2 == null)
return true;
/* If one of the trees is NULL and other is not,
then return false */
if (n1 == null || n2 == null)
return false;
/* Otherwise check if left and right subtrees are
mirrors of their counterparts */
return IsFoldableUtil(n1.left, n2.right)
&& IsFoldableUtil(n1.right, n2.left);
}
/* Driver code */
public static void Main(String[] args)
{
BinaryTree tree = new BinaryTree();
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
if (tree.IsFoldable(tree.root))
Console.WriteLine("tree is foldable");
else
Console.WriteLine("Tree is not foldable");
}
}
/* This code contributed by PrinciRaj1992 */
Javascript
输出
tree is foldable
迭代方法:这个想法是使用队列来遍历树并使用 BFS 方法。
为了证明它是可折叠树,我们需要检查两个条件是否为空。
- 左子树的左孩子=右子树的右孩子。它们都不应为空。
- 左子树的右孩子 = 右子树的左孩子。它们都应该为空或不为空。
下面是上述方法的实现:
Java
// Java code for the above approach
import java.util.Queue;
import java.util.LinkedList;
public class FoldableTrees {
Node root = null;
// Class Node to store the data and left and right pointers
class Node {
int key;
Node left;
Node right;
Node(int key) {
this.key = key;
left = right = null;
}
}
// Function to find whether the tree is foldable
boolean isFoldable() {
// Queue to store visited nodes
Queue q = new LinkedList<>();
// Initially add the left and right nodes of root
if (root != null) {
q.add(root.left);
q.add(root.right);
}
while (!q.isEmpty()) {
// Remove the front 2 nodes to
// check for null condition
Node p = q.remove();
Node r = q.remove();
// If both are null, continue and check
// the further elements
if (p == null && r == null)
continue;
// If one of them is not null, then return false
if ((p == null && r != null) || (p != null && r == null))
return false;
/* Insert in the same order:
1. left of left subtree
2. right of right subtree
3.right of left subtree
4.left of right subtree */
q.add(p.left);
q.add(r.right);
q.add(p.right);
q.add(r.left);
}
// Only if the tree is foldable
return true;
}
// Driver code
public static void main(String args[]) {
FoldableTrees tree = new FoldableTrees();
// Insert data into the tree
tree.root = tree.new Node(1);
tree.root.left = tree.new Node(2);
tree.root.right = tree.new Node(3);
tree.root.right.left = tree.new Node(4);
tree.root.left.right = tree.new Node(5);
// Function call
if(tree.isFoldable())
System.out.println("Tree is foldable");
else
System.out.println("Tree is not foldable");
}
}
//This method is contributed by likhita AVL
C#
using System;
using System.Collections.Generic;
public class Node
{
public int key;
public Node left,right;
public Node(int key)
{
this.key=key;
this.left=this.right=null;
}
}
public class FoldableTrees
{
Node root = null;
// Function to find whether the tree is foldable
bool isFoldable() {
// Queue to store visited nodes
Queue q = new Queue();
// Initially add the left and right nodes of root
if (root != null) {
q.Enqueue(root.left);
q.Enqueue(root.right);
}
while (q.Count!=0) {
// Remove the front 2 nodes to
// check for null condition
Node p = q.Dequeue();
Node r = q.Dequeue();
// If both are null, continue and check
// the further elements
if (p == null && r == null)
continue;
// If one of them is not null, then return false
if ((p == null && r != null) || (p != null && r == null))
return false;
/* Insert in the same order:
1. left of left subtree
2. right of right subtree
3.right of left subtree
4.left of right subtree */
q.Enqueue(p.left);
q.Enqueue(r.right);
q.Enqueue(p.right);
q.Enqueue(r.left);
}
// Only if the tree is foldable
return true;
}
// Driver code
static public void Main ()
{
FoldableTrees tree = new FoldableTrees();
// Insert data into the tree
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
// Function call
if(tree.isFoldable())
Console.WriteLine("Tree is foldable");
else
Console.WriteLine("Tree is not foldable");
}
}
// This code is contributed by patel2127.
Javascript
输出
Tree is foldable