给定一棵二叉树,任务是检查它是否由在偶数级严格递增且在奇数级严格递减的节点值组成(假设根节点在级别0 )。
例子:
Input:
Output: YES
Explanation:
At level 1 (odd), Node values 6 and 3 are in strictly decreasing order.
At level 2 (even), Node values 4, 7, and 11 are in strictly increasing order.
At level 3 (odd), Node values 10, 5, and 1) are in strictly decreasing order.
Therefore, the tree satisfies the given conditions.
Input:
Output: NO
方法:想法是在给定的二叉树上执行层序遍历,对于每一层,检查它是否满足给定的条件。请按照以下步骤解决问题:
- 创建一个空的Queue,在树的Level Order Traversal过程中将每一层的节点一一存储。
- 将根节点推入队列。
- 迭代直到队列为空并执行以下操作:
- 保持从队列中弹出当前级别的节点并将其插入到 Arraylist 中。将其所有子节点推入Queue 。
- 如果级别是偶数,请检查 Arraylist 中存在的元素是否按递增顺序排列。如果发现是真的,则进入下一个级别。否则,打印No 。
- 同样,检查奇数级别。
- 完全遍历树后,如果发现所有级别都满足条件,则打印YES 。
下面是上述方法的实现:
C++
2
/ \
6 3
/ \ \
4 7 11
/ \ \
10 5 1
Java
5
/ \
6 3
/ \ \
4 9 2
Python3
// C++ program for the above approach
#include
using namespace std;
struct Node
{
int val;
Node *left, *right;
};
struct Node* newNode(int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->val = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Function to check if given binary
// tree satisfies the required conditons
bool checkEvenOddLevel(Node *root)
{
if (root == NULL)
return true;
// Queue to store nodes
// of each level
queue q;
q.push(root);
// Stores the current
// level of the binary tree
int level = 0;
// Traverse until the
// queue is empty
while (q.empty())
{
vector vec;
// Stores the number of nodes
// present in the current level
int size = q.size();
for(int i = 0; i < size; i++)
{
Node *node = q.front();
vec.push_back(node->val);
// Insert left and right child
// of node into the queue
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
// If the level is even
if (level % 2 == 0)
{
// If the nodes in this
// level are in strictly
// increasing order or not
for(int i = 0; i < vec.size() - 1; i++)
{
if (vec[i + 1] > vec[i])
continue;
return false;
}
}
// If the level is odd
else if (level % 2 == 1)
{
// If the nodes in this
// level are in strictly
// decreasing order or not
for(int i = 0; i < vec.size() - 1; i++)
{
if (vec[i + 1] < vec[i])
continue;
return false;
}
}
// Increment the level count
level++;
}
return true;
}
// Driver Code
int main()
{
// Construct a Binary Tree
Node *root = NULL;
root = newNode(2);
root->left = newNode(6);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(7);
root->right->right = newNode(11);
root->left->left->left = newNode(10);
root->left->left->right = newNode(5);
root->left->right->right = newNode(1);
// Function Call
if (checkEvenOddLevel(root))
cout << "YES";
else
cout << "NO";
}
// This code is contributed by ipg2016107
C#
// Java Program for the above approach
import java.util.*;
class GFG {
// Structure of Tree node
static class Node {
int val;
Node left, right;
}
// Function to create new Tree node
static Node newNode(int data)
{
Node temp = new Node();
temp.val = data;
temp.left = null;
temp.right = null;
return temp;
}
// Function to check if given binary
// tree satisfies the required conditons
public static boolean
checkEvenOddLevel(Node root)
{
if (root == null)
return true;
// Queue to store nodes
// of each level
Queue q
= new LinkedList<>();
q.add(root);
// Stores the current
// level of the binary tree
int level = 0;
// Traverse until the
// queue is empty
while (!q.isEmpty()) {
ArrayList list
= new ArrayList<>();
// Stores the number of nodes
// present in the current level
int size = q.size();
for (int i = 0; i < size; i++) {
Node node = q.poll();
list.add(node.val);
// Insert left and right child
// of node into the queue
if (node.left != null)
q.add(node.left);
if (node.right != null)
q.add(node.right);
}
// If the level is even
if (level % 2 == 0) {
// If the nodes in this
// level are in strictly
// increasing order or not
for (int i = 0; i < list.size() - 1;
i++) {
if (list.get(i + 1) > list.get(i))
continue;
return false;
}
}
// If the level is odd
else if (level % 2 == 1) {
// If the nodes in this
// level are in strictly
// decreasing order or not
for (int i = 0; i < list.size() - 1;
i++) {
if (list.get(i + 1) < list.get(i))
continue;
return false;
}
}
// Increment the level count
level++;
}
return true;
}
// Driver Code
public static void main(String[] args)
{
// Construct a Binary Tree
Node root = null;
root = newNode(2);
root.left = newNode(6);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(7);
root.right.right = newNode(11);
root.left.left.left = newNode(10);
root.left.left.right = newNode(5);
root.left.right.right = newNode(1);
// Function Call
if (checkEvenOddLevel(root)) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
输出:
# Python3 program for the above approach
# Tree node
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.val = data
# Function to return new tree node
def newNode(data):
temp = Node(data)
return temp
# Function to check if the
# tree is even-odd tree
def checkEvenOddLevel(root):
if (root == None):
return True
q = []
# Stores nodes of each level
q.append(root)
# Store the current level
# of the binary tree
level = 0
# Traverse until the
# queue is empty
while (len(q) != 0):
l = []
# Stores the number of nodes
# present in the current level
size = len(q)
for i in range(size):
node = q[0]
q.pop(0)
# Insert left and right child
# of node into the queue
if (node.left != None):
q.append(node.left);
if (node.right != None):
q.append(node.right);
# If the level is even
if (level % 2 == 0):
# If the nodes in this
# level are in strictly
# increasing order or not
for i in range(len(l) - 1):
if (l[i + 1] > l[i]):
continue
return False
# If the level is odd
elif (level % 2 == 1):
# If the nodes in this
# level are in strictly
# decreasing order or not
for i in range(len(l) - 1):
if (l[i + 1] < l[i]):
continue
return False
# Increment the level count
level += 1
return True
# Driver code
if __name__=="__main__":
# Construct a Binary Tree
root = None
root = newNode(2)
root.left = newNode(6)
root.right = newNode(3)
root.left.left = newNode(4)
root.left.right = newNode(7)
root.right.right = newNode(11)
root.left.left.left = newNode(10)
root.left.left.right = newNode(5)
root.left.right.right = newNode(1)
# Check if the binary tree
# is even-odd tree or not
if (checkEvenOddLevel(root)):
print("YES")
else:
print("NO")
# This code is contributed by rutvik_56
时间复杂度: O(N)
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live