📜  检查 BST 是否包含 Dead End

📅  最后修改于: 2021-10-27 16:53:43             🧑  作者: Mango

给定一个包含大于 0 的正整数值的二叉搜索树。任务是检查 BST 是否包含死胡同。这里的死胡同意味着,我们无法在该节点之后插入任何元素。
例子:

Input :        8
             /   \ 
           5      9
         /   \
        2     7
       /
      1               
Output : Yes
Explanation : Node "1" is the dead End because
         after that we cant insert any element.       

Input :       8
            /   \ 
           7     10
         /      /   \
        2      9     13

Output : Yes
Explanation : We can't insert any element at 
              node 9.  

如果我们仔细观察这个问题,我们可以注意到,我们基本上需要检查是否存在值为 x 的叶节点,使得 x+1 和 x-1 存在于 BST 中,x = 1 除外。对于 x = 1,我们不能插入 0,因为问题陈述说 BST 只包含正整数。
为了实现上述想法,我们首先遍历整个 BST 并将所有节点存储在 hash_map 中。我们还将所有叶子存储在单独的哈希中,以避免重新遍历 BST。最后,我们检查每个叶节点 x,是否在 hash_map 中存在 x-1 和 x+1。
下面是上述想法的 C++ 实现。

C++
// C++ program check weather BST contains
// dead end or not
#include
using namespace std;
 
// A BST node
struct Node
{
    int data;
    struct Node *left, *right;
};
 
// A utility function to create a new node
Node *newNode(int data)
{
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
/* A utility function to insert a new Node
  with given key in BST */
struct Node* insert(struct Node* node, int key)
{
    /* If the tree is empty, return a new Node */
    if (node == NULL) return newNode(key);
 
    /* Otherwise, recur down the tree */
    if (key < node->data)
        node->left = insert(node->left, key);
    else if (key > node->data)
        node->right = insert(node->right, key);
 
    /* return the (unchanged) Node pointer */
    return node;
}
 
// Function to store all node of given binary search tree
void storeNodes(Node * root, unordered_set &all_nodes,
                          unordered_set &leaf_nodes)
{
    if (root == NULL)
        return ;
 
    // store all node of binary search tree
    all_nodes.insert(root->data);
 
    // store leaf node in leaf_hash
    if (root->left==NULL && root->right==NULL)
    {
        leaf_nodes.insert(root->data);
        return ;
    }
 
    // recur call rest tree
    storeNodes(root-> left, all_nodes, leaf_nodes);
    storeNodes(root->right, all_nodes, leaf_nodes);
}
 
// Returns true if there is a dead end in tree,
// else false.
bool isDeadEnd(Node *root)
{
    // Base case
    if (root == NULL)
        return false ;
 
    // create two empty hash sets that store all
    // BST elements and leaf nodes respectively.
    unordered_set all_nodes, leaf_nodes;
 
    // insert 0 in 'all_nodes' for handle case
    // if bst contain value 1
    all_nodes.insert(0);
 
    // Call storeNodes function to store all BST Node
    storeNodes(root, all_nodes, leaf_nodes);
 
    // Traversal leaf node and check Tree contain
    // continuous sequence of
    // size tree or Not
    for (auto i = leaf_nodes.begin() ; i != leaf_nodes.end(); i++)
    {
        int x = (*i);
 
        // Here we check first and last element of
        // continuous sequence that are x-1 & x+1
        if (all_nodes.find(x+1) != all_nodes.end() &&
            all_nodes.find(x-1) != all_nodes.end())
            return true;
    }
 
    return false ;
}
 
// Driver program
int main()
{
/*       8
       /   \
      5    11
     /  \
    2    7
     \
      3
       \
        4 */
    Node *root = NULL;
    root = insert(root, 8);
    root = insert(root, 5);
    root = insert(root, 2);
    root = insert(root, 3);
    root = insert(root, 7);
    root = insert(root, 11);
    root = insert(root, 4);
    if (isDeadEnd(root) == true)
        cout << "Yes " << endl;
    else
        cout << "No " << endl;
    return 0;
}


Python3
# Python 3 program check
# weather BST contains
# dead end or not
all_nodes = set()
leaf_nodes = set()
 
# A BST node
class newNode:
   
    def __init__(self, data):
       
        self.data = data
        self.left = None
        self.right = None
 
''' A utility function to
    insert a new Node with
    given key in BST '''
def insert(node, key):
   
    '''/* If the tree is empty,
          return a new Node */ '''
    if (node == None):
        return newNode(key)
 
    # Otherwise, recur down
    # the tree
    if (key < node.data):
        node.left = insert(node.left,
                           key)
    elif (key > node.data):
        node.right = insert(node.right,
                            key)
 
    # return the (unchanged)
    # Node pointer
    return node
 
# Function to store all node
# of given binary search tree
def storeNodes(root):
   
    global all_nodes
    global leaf_nodes
    if (root == None):
        return
 
    # store all node of binary
    # search tree
    all_nodes.add(root.data)
 
    # store leaf node in leaf_hash
    if (root.left == None and
        root.right == None):
        leaf_nodes.add(root.data)
        return
 
    # recur call rest tree
    storeNodes(root. left)
    storeNodes(root.right)
 
# Returns true if there is
# a dead end in tree,
# else false.
def isDeadEnd(root):
   
    global all_nodes
    global leaf_nodes
     
    # Base case
    if (root == None):
        return False
 
    # create two empty hash
    # sets that store all BST
    # elements and leaf nodes
    # respectively.
 
    # insert 0 in 'all_nodes'
    # for handle case if bst
    # contain value 1
    all_nodes.add(0)
 
    # Call storeNodes function
    # to store all BST Node
    storeNodes(root)
 
    # Traversal leaf node and
    # check Tree contain
    # continuous sequence of
    # size tree or Not
    for x in leaf_nodes:
       
        # Here we check first and
        # last element of continuous
        # sequence that are x-1 & x+1
        if ((x + 1) in all_nodes and
            (x - 1) in all_nodes):
            return True
 
    return False
 
# Driver code
if __name__ == '__main__':
   
    '''/*       8
       /   \
      5    11
     /  \
    2    7
     \
      3
       \
        4 */
    '''
    root = None
    root = insert(root, 8)
    root = insert(root, 5)
    root = insert(root, 2)
    root = insert(root, 3)
    root = insert(root, 7)
    root = insert(root, 11)
    root = insert(root, 4)
     
    if(isDeadEnd(root) == True):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by bgangwar59


输出:

Yes


如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。