📌  相关文章
📜  检查二叉树是否包含按偶数和奇数级别严格按升序和降序排列的节点值

📅  最后修改于: 2021-04-29 11:28:49             🧑  作者: Mango

给定一棵二叉树,任务是检查它是否包含按偶数级严格递增顺序和按奇数级严格递减排列的节点值(假定根节点的级别为0 )。

例子:

方法:想法是对给定的二叉树执行级别顺序遍历,并针对每个级别检查其是否满足给定条件。请按照以下步骤解决问题:

  • 创建一个空队列,以在树的“层顺序遍历”期间一个接一个地存储每个层的节点。
  • 将根节点推入队列。
  • 迭代直到队列为空,然后执行以下操作:
    • 保持从队列中弹出当前级别的节点,并将其插入到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)