How to validate a Binary Tree?

时间:2018-04-18 18:03:57

标签: tree binary-tree binary-search-tree binary-search b-tree

I have been doing some digging around Binary Tree and Binary Source Tree. Ran into this very fundamental question of the Tree (BT) and challenges the properties of a Binary Tree to be proven.


Question: Given a node (the root), check if this is a valid Binary Tree. Not asking to validate if given BT is a BST, but simply asking to check if below is a BT.

Valid:
  X1
 /  \
X4   X5
 \    \
  X3   X7

Invalid:
  X1
 /  \
X4   X5
 \  /  \
  X3   X7


# A Python class that represents an individual node in a BT
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key 

    def isNotBinaryTree(root):
        # code here

if isNotBinaryTree(root):
   print "True"
else: 
   print "False"

I do know this is NOT a binary tree (in fact, this is not even a tree by its definition and properties). Thing is... how do I prove or validate this? Or how do I validate this is not a BT where x4 and x5 -> x3 (multiple parent (nodes) point to a same child node? ***No data provided! What would the algorithm/logic look like if I were to solve this? (Python x.x preferred)

2 个答案:

答案 0 :(得分:0)

考虑到你的数据结构,接收一个节点并递归地查看是否存在一个具有简单函数的循环应该非常容易:

def hasCycle(node, seen = set()):
    if node in seen: return True
    seen.add(node)
    if node.left and hasCycle(node.left, seen): 
        return True
    if node.right and hasCycle(node.right, seen): 
        return True
    return False

这只是进行深度优先搜索并保持一组访问的节点。如果你看到一个节点两次,那就是一个循环。

答案 1 :(得分:0)

按照以下链接获取有关BT / BST的更多详细说明: https://en.wikipedia.org/wiki/Tree_traversal

def nodes_visited(root, key):
    if root.next:
        if root.next in key: 
            return True
        key.append(root)
        return nodes_visited(root.next, key)
    return False

def has_cycle(head):
    return nodes_visited(root=head, key=[])