📜  检查二叉树是否为偶数奇数树

📅  最后修改于: 2021-04-23 20:56:28             🧑  作者: Mango

给定一棵二叉树,任务是检查该二叉树是否为偶数奇数二叉树。

例子:

方法:请按照以下步骤解决问题:

  1. 这个想法是执行级别顺序遍历,并检查偶数级别上存在的节点是否为偶数,奇数级别上存在的节点是否为奇数。
  2. 如果发现任何处于奇数级的节点具有奇数值,反之亦然,则打印“ NO ”。
  3. 否则,在完全遍历树后,打印“”。

下面是上述方法的实现:

C++
2
            / \
           3   9
          / \   \
         4   10  6


Java
4
            / \
           3   7
          / \   \
         4   10  5


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 the
// tree is even-odd tree
bool isEvenOddBinaryTree(Node *root)
{
    if (root == NULL)
        return true;
 
    // Stores nodes of each level
    queue q;
    q.push(root);
 
    // Store the current level
    // of the binary tree
    int level = 0;
 
    // Traverse until the
    // queue is empty
    while (!q.empty())
    {
         
        // 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();
             
            // Check if the level
            // is even or odd
            if (level % 2 == 0)
            {
                if (node->val % 2 == 1)
                    return false;
            }
            else if (level % 2 == 1)
            {
                if (node->val % 2 == 0)
                    return true;
            }
 
            // Add the nodes of the next
            // level into the queue
            if (node->left != NULL)
            {
                q.push(node->left);
            }
            if (node->right != NULL)
            {
                q.push(node->right);
            }
        }
 
        // Increment the level count
        level++;
    }
    return true;
}
 
// Driver Code
int main()
{
     
    // Construct a Binary Tree
    Node *root = NULL;
    root = newNode(2);
    root->left = newNode(3);
    root->right = newNode(9);
    root->left->left = newNode(4);
    root->left->right = newNode(10);
    root->right->right = newNode(6);
 
    // Check if the binary tree
    // is even-odd tree or not
    if (isEvenOddBinaryTree(root))
        cout << "YES";
    else
        cout << "NO";
}
 
// This code is contributed by ipg2016107


C#
// Java Program for the above approach
import java.util.*;
 
class GfG {
 
    // Tree node
    static class Node {
        int val;
        Node left, right;
    }
 
    // Function to return 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 the
    // tree is even-odd tree
    public static boolean
    isEvenOddBinaryTree(Node root)
    {
        if (root == null)
            return true;
 
        // Stores nodes of each level
        Queue q
            = new LinkedList<>();
        q.add(root);
 
        // Store the current level
        // of the binary tree
        int level = 0;
 
        // Traverse until the
        // queue is empty
        while (!q.isEmpty()) {
 
            // 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();
 
                // Check if the level
                // is even or odd
                if (level % 2 == 0) {
 
                    if (node.val % 2 == 1)
                        return false;
                }
                else if (level % 2 == 1) {
 
                    if (node.val % 2 == 0)
                        return false;
                }
 
                // Add the nodes of the next
                // level into the queue
                if (node.left != null) {
 
                    q.add(node.left);
                }
                if (node.right != null) {
 
                    q.add(node.right);
                }
            }
 
            // 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(3);
        root.right = newNode(9);
        root.left.left = newNode(4);
        root.left.right = newNode(10);
        root.right.right = newNode(6);
 
        // Check if the binary tree
        // is even-odd tree or not
        if (isEvenOddBinaryTree(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 isEvenOddBinaryTree(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):
  
        # Stores the number of nodes
        # present in the current level
        size = len(q)
         
        for i in range(size):
            node = q[0]
            q.pop(0)
  
            # Check if the level
            # is even or odd
            if (level % 2 == 0):
  
                if (node.val % 2 == 1):
                    return False
                 
                elif (level % 2 == 1):
                    if (node.val % 2 == 0):
                        return False
                 
                # Add the nodes of the next
                # level into the queue
                if (node.left != None):
                    q.append(node.left)
                 
                if (node.right != None):
                    q.append(node.right)
                 
            # 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(3)
    root.right = newNode(9)
    root.left.left = newNode(4)
    root.left.right = newNode(10)
    root.right.right = newNode(6)
  
    # Check if the binary tree
    # is even-odd tree or not
    if (isEvenOddBinaryTree(root)):
        print("YES")
    else:
        print("NO")
        
# This code is contributed by rutvik_56

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