Playground Design Karl Lieberherr Playground A collection of
Playground Design Karl Lieberherr
Playground • A collection of algorithms to define – what is wanted from a solve algorithm S in a particular domain (inputs/outputs) – how S is evaluated (quality) – what kind of claims can be made about S (expression with quantifiers) • A playground defines the WHAT is desired about S and the avatars define the HOW S is implemented.
HSR Playground, valid • When is a solution valid? • Requirements for a valid solution (Dennis): - Strictly binary tree (2 -tree) - Tree is ordered: < to the left, ≥ to the right - Exactly n leaf nodes in [0, n-1] with no repeats - Exactly n-1 question nodes in [1, n-1] with no repeats - No more than k subsequent left branches
valid • Requirements for valid (Karl) • A decision tree for HSR(n, k) is valid if (1) the tree is a binary search tree with inner nodes 1. . n-1 exactly once and leaves 0. . n-1 exactly once (left nodes are < root, right nodes >= root, for all subtrees). (2) all paths from the root to a leaf have at most k left branches.
Binary Search Trees = Ordered Binary Trees • From: http: //cslibrary. stanford. edu/110/Binary. Trees. ht ml • A "binary search tree" (BST) or "ordered binary tree" is a type of binary tree where the nodes are arranged in order: for each node, all elements in its left subtree are less-or-equal to the node (<=), and all the elements in its right subtree are greater than the node (>). • We <= becomes < and > becomes >=.
Examples • 5 -> TRUE / 2 7 • 5 -> FALSE / 2 7 / 1 6
Efficient • 14. is. BST() -- version 2 • Version 1 above runs slowly since it traverses over some parts of the tree many times. A better solution looks at each node only once. The trick is to write a utility helper function is. BSTRecur(struct node* node, int min, int max) that traverses down the tree keeping track of the narrowing min and max allowed values as it goes, looking at each node only once. The initial values for min and max should be INT_MIN and INT_MAX -- they narrow from there.
is. BST 2 • /* Returns true if the given tree is a binary search tree (efficient version). */ int is. BST 2(struct node* node) { return(is. BSTRecur(node, INT_MIN, INT_MAX)); }
is. BSTUtil • /* Returns true if the given tree is a BST and its values are >= min and <= max. */ int is. BSTUtil(struct node* node, int min, int max) {
is. BSTUtil • /* Returns true if the given tree is a BST and its values are >= min and <= max. */ int is. BSTUtil(struct node* node, int min, int max) { if (node==NULL) return(true); • // false if this node violates the min/max constraint if (node->data<min || node->data>max) return(false); • // otherwise check the subtrees recursively, // tightening the min or max constraint return is. BSTUtil(node->left, min, node->data) && is. BSTUtil(node->right, node->data+1, max) ); }
- Slides: 11