def str2tree(self, s):
        """
        follow-up: convert string to tree
        """
        if not s:
            return None

        index = s.find('(')
        if index == -1:
            return TreeNode(int(s))

        # find the position of ')' which matches the first '('
        unbalanced, i = 0, 0
        for i, c in enumerate(s):
            if c == '(':
                unbalanced += 1
            elif c == ')':
                unbalanced -= 1
                if unbalanced == 0:
                    break

        # create treenode for root, and left subtree string, right subtree string
        root = TreeNode(int(s[:index]))
        left_s = s[index + 1:i]
        right_s = s[i + 2:-1]

        root.left = self.str2tree(left_s)
        root.right = self.str2tree(right_s)

        return root
예제 #2
0
def simple_exp(synchset):
    pass
    global token
    t = TreeNode()
    firstset = ["TKN_LPAREN", "TKN_NUM", "TKN_ID"]
    synchset += ["TKN_LESS", "TKN_ELESS", "TKN_MORE", "TKN_EMORE", "TKN_EQUAL", "TKN_NEQUAL"]
    checkinput(firstset, synchset)

    if not token.tipo in synchset:
        t = term(synchset)

        while (token.tipo == "TKN_ADD") | (token.tipo == "TKN_MINUS"):
            p = newExpNode(ExpKind.OpK)

            if p is not None:
                p.branch[0] = t
                p.attr.op = token.tipo
                t = p

                match(token.tipo)
                # En caso de que haya dos operadores seguidos:
                while (token.tipo == "TKN_ADD") | (token.tipo == "TKN_MINUS"):
                    print("Syntax error, multiple operator detected at column " + token.columna + " at line " +
                          token.linea)
                    output.write("Syntax error, multiple operator detected at column " + token.columna +
                                 " at line " + token.linea + "\n")
                    token = getToken()
                t.branch[1] = term(synchset)
        checkinput(synchset, firstset)
    return t
예제 #3
0
def expresion(synchset):
    pass
    global token
    t = TreeNode()
    firstset = ["TKN_LPAREN", "TKN_ID", "TKN_NUM"]
    synchset += []
    checkinput(firstset, synchset)

    if not token.tipo in synchset:
        t = simple_exp(synchset)

        if isLogic():
            p = newExpNode(ExpKind.OpK)

            if p is not None:
                p.branch[0] = t
                p.attr.op = token.tipo
                t = p

            match(token.tipo)

            if t is not None:
                t.branch[1] = simple_exp(synchset)
        checkinput(synchset, firstset)
    return t
예제 #4
0
def main():
    pass
    global token, tokens
    t = TreeNode()

    if token.tipo == "TKN_EOF":
        print("Empty file")
    else:
        firstset = ["TKN_MAIN"]
        synchset = ["TKN_EOF"]
        checkinput(firstset, synchset)

        if not token.tipo in synchset:
            t = newStmtNode(StmtKind.MainK)
            match("TKN_MAIN")
            match("TKN_LBRACE")

            if t is not None:
                t.branch[0] = stmt_sequence(["TKN_RBRACE"])
            try:
                match("TKN_RBRACE")
            except:
                # tokAux = tokens[contador-1]
                # longitud = (float(tokAux.columna) + len(tokAux.lexema))-1
                # print("Syntax error, was expected '}' after column " + longitud + " at line " + tokAux.linea)
                # output.write("Syntax error, was expected '}' after column " + tokAux.columna + " at line " +
                #              tokAux.linea + "\n")
                pass

    return t
예제 #5
0
 def evaluateStatement(self, sub, subParent, code):
     #parse statement
     parseCode = TreeNode(self.head)
     outSignal = self.FAILED  #short circuit eval
     for unit in sub:
         if unit == '~':  #continue after this statement
             outSignal = self.CONTINUE  #can continue checking subParent
             #pass this extra symbol
         elif unit[0] == '{' and unit != '{':
             code = self.evaluateBraces(unit, code, parseCode)
         elif unit[0] == '[' and unit != '[':
             #print("INTO THE BRACKETS WE GO BECAUSE OF",unit)
             code = self.evaluateBrackets(unit, code, parseCode)
         elif (unit[0].isupper() and unit[1].islower() and unit != "Literal"
               and unit != 'Identifier'):  #nonterminal
             child = self.visit(unit, code)
             if child.passed:
                 parseCode.addChild(child.parseCode)
                 code = child.code
             else:
                 return outSignal, parseCode, code
         else:  #terminal
             outcome, code = self.evaluateTerminal(unit, code, parseCode)
             #destructively alters parseCode and code
             if not outcome:
                 return outSignal, parseCode, code
     return self.PASSED, parseCode, code
예제 #6
0
    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        ss = data.split(',')
        if not ss:
            return None
        root = TreeNode(int(ss[0]))
        i, q = 1, deque([root])

        while i < len(ss):
            node = q.popleft()
            left = ss[i]
            i += 1
            if left != 'null':
                node.left = TreeNode(int(left))
                q.append(node.left)
            if i < len(ss):
                right = ss[i]
                i += 1
                if right != 'null':
                    node.right = TreeNode(int(right))
                    q.append(node.right)
        
        return root
예제 #7
0
 def build(self, vals, left, right):
     if vals and left < vals[0] < right:
         val = vals.pop(0)
         node = TreeNode(val)
         node.left = self.build(vals, left, val)
         node.right = self.build(vals, val, right)
         return node
예제 #8
0
    def ordInsert(self, value):
        ''' perform BST ordered insert'''
        def TreeNodeInsert(tnode, value):
            ''' perform ordered insert recursively on TreeNode structure'''
            if tnode._data <= value:
                # insert right
                if tnode._right is None:
                    tnode._right = Tn.TreeNode(value)
                else:
                    TreeNodeInsert(tnode._right, value)
            else:
                # insert left
                if tnode._left is None:
                    tnode._left = Tn.TreeNode(value)
                else:
                    TreeNodeInsert(tnode._left, value)
            return

        if (self.root == None):
            self.root = Tn.TreeNode(value)
            self.size += 1
        elif (self.root._data > value):
            if (self.root._left is None):
                self.root._left = Tn.TreeNode(value)
            else:
                TreeNodeInsert(self.root._left, value)
        else:
            if (self.root._right is None):
                self.root._right = Tn.TreeNode(value)
            else:
                TreeNodeInsert(self.root._right, value)
예제 #9
0
    def constructMaximumBinaryTree3(self, nums):
        """
        Fastest, O(n)
        We keep track of a stack, and make sure the numbers in stack is in decreasing order.

        For each new num, we make it into a TreeNode first.
        Then:

        0. If stack is empty, we push the node into stack and continue
        1. If new value is smaller than the node value on top of the stack, we append TreeNode as the right node of top of stack.
        2. If new value is larger, we keep poping from the stack until the stack is empty OR top of stack node value is greater than the new value. During the pop, we keep track of the last node being poped.
        After step 2, we either in the situation of 0, or 1, either way, we append last node as left node of the new node.
        After traversing, the bottom of stack is the root node because the bottom is always the largest value we have seen so far (during the traversing of list).

        """
        if not nums:
            return None
        stack = []
        last = None
        for num in nums:
            while stack and stack[-1].val < num:
                last = stack.pop()
            node = TreeNode(num)
            if stack:
                stack[-1].right = node
            if last:
                node.left = last
            stack.append(node)
            last = None
        return stack[0]
 def buidTree(self, arr, left, right):
     if left == right: return None
     mid = (left + right) / 2
     root = TreeNode(arr[mid])
     root.left = self.buidTree(arr, left, mid)
     root.right = self.buidTree(arr, mid + 1, right)
     return root
예제 #11
0
    def _insert_help(self, t, value):
        '''private helper method to insert value into AVL (sub)tree with
        root node t'''

        if t is None:
            t = TreeNode(value)

        elif value < t.item:  # inserting into the left subtree
            t.left = self._insert_help(t.left, value)
            # left subtree height may be now larger than right subtree
            if get_height(t.left) - get_height(t.right) == 2:
                # determine which subtree the new value was inserted
                if value < t.left.item:
                    # insertion into left subtree of left child: single rotation
                    t = self._left_single_rotate(t)
                else:
                    # insertion into right subtree of left child: double rotation
                    t = self._right_left_rotate(t)

        else:  # inserting into the right subtree
            if value > t.item:
                t.right = self._insert_help(t.right, value)
            if get_height(t.right) - get_height(t.left) == 2:
                if value > t.right.item:
                    t = self._right_single_rotate(t)
                else:
                    t = self._left_right_rotate(t)
            # exercise for reader

        # update height of tree rooted at t
        t.height = max(get_height(t.left), get_height(t.right)) + 1
        return t
 def buidTree(self,arr,left, right):
     if left == right: return None
     mid = (left + right) / 2
     root = TreeNode(arr[ mid ])
     root.left = self.buidTree(arr, left, mid)
     root.right = self.buidTree(arr, mid+1, right)
     return root
예제 #13
0
    def insert(self, segment, bottom_segment=None, x=None):
        key = segment.key

        if not self.root:
            self.root = TreeNode(segment,
                                 color=BLACK,
                                 parent=None,
                                 left=self.NIL_LEAF,
                                 right=self.NIL_LEAF,
                                 bottom_segment=bottom_segment)
            self.count += 1
            return
        parent, node_dir = self._find_parent(key, x)
        if node_dir is None:
            return
        new_node = TreeNode(segment=segment,
                            color=RED,
                            parent=parent,
                            left=self.NIL_LEAF,
                            right=self.NIL_LEAF,
                            bottom_segment=bottom_segment)
        if node_dir == 'L':
            parent.left = new_node
        else:
            parent.right = new_node

        self._try_rebalance(new_node)
        self.count += 1
예제 #14
0
 def buildTree(self, nums, left, right):
     if right == left: return None
     mid = (left + right) / 2
     root = TreeNode(nums[mid])
     root.left = self.buildTree(nums, left, mid)
     root.right = self.buildTree(nums, mid + 1, right)
     return root
예제 #15
0
def _horizontal_cut(node, DB_equ_eps, ordered_RD, ordered_CD):
    """
    Extract cluster information in a DBSCAN-like method.

    ordered_RD:
        the reachability distance correspond to each point in ordered list produced by OPTICS.
    node:
        a node class that represents cluster. ideally, this is leaf node.
    DB_equ_eps:
        DBSCAN equivalent eps (also called dmax in IVAS)
    """
    ##-------------------------------------------------------------------------
    # Note that this is a modified version of the DBSCAN-like method described in Sander's paper.
    # If we alwasy start from the index 0 of current RD, then Sander's method works perfectly.
    #
    # However, current method will be used to refining nodes, which could be start from any between 0 to len(RD).
    # Thus a modification is requied.
    #
    # The issue lie in the index 'start'. In the original algorithm in Sander's paper, since RD[0] is always nan
    # therefore condition '(RD > eps or RD is nan) and (CD < eps)' always works to initiate a new cluster.
    # In our case, the node in the middle would have a value RD, which may or may not larger than eps.
    # This caused the algorithm unable to initialize a new cluster until it meet a new RD > eps in current node,
    # even if the CD < eps is met from the beginning. This is problematic, since in the original way, CD < eps will
    # always be included in a cluster, while in our case is descarded. Note this issue is only for the first index
    # element. Changing the new cluster initialization at the first index would solve this issue.
    #
    # The new condition for  a new cluster:
    #       1. (RD > eps or RD is nan) and (CD < eps)
    #       2. RD <= eps and CD < eps
    ##-------------------------------------------------------------------------
    start, end = node.index_range

    if ordered_CD[start] >= DB_equ_eps:
        is_in_cluster = False
    else:
        is_in_cluster = True
        new_start = start
        new_end = start + 1

    # Normal density cut clustering start
    for idx in range(start + 1, end):
        if ordered_RD[idx] >= DB_equ_eps or np.isnan(ordered_RD[idx]):
            if is_in_cluster:  # if previous point still in cluster, save 'new_start' to 'new_end' as a new cluster
                new_node = TreeNode.TreeNode(new_start, new_end, heapdict())
                node.add_child(new_node)

            if ordered_CD[idx] < DB_equ_eps:  # initiate a new cluster
                is_in_cluster = True
                new_start = idx
                new_end = new_start + 1
            else:  # RD > eps and CD > eps, does not belong to any cluster.
                is_in_cluster = False

        elif is_in_cluster:  # if RD < eps and RD is not nan, and in cluster track
            if idx < end - 1:
                new_end += 1
            elif idx == end - 1:
                new_node = TreeNode.TreeNode(new_start, idx, heapdict())
                node.add_child(new_node)
    return
    def insert(self, value, node=""):

        if node == "":  # value를 연결할 노드가 없다면
            node = self.root  # root를 노드라고 생각한다
        if self.root == "":  # root가 지정되어 있지 않다면
            self.root = TreeNode(value, "")  # root를 지정한다
            return

        # 삽입할려는 value가 기존 노드의 value와 같다면 끝
        if value == node.getValue():
            return

        #  삽입할려는 value가 기존 노드의 value보다 크다면
        if value > node.getValue():
            if node.getRHS() == "":  # 오른쪽이 비어 있다면
                node.setRHS((TreeNode(value, node)))
            else:  # 기존에 오른쪽에 지정된 것이 있다면
                self.insert(value,
                            node.getRHS())  # recursion : node.getRHS가 중심이 된다.

        #  삽입할려는 value가 기존 노드의 value보다 작다면
        if value < node.getValue():
            if node.getLHS() == "":  # 지정된 것이 없다면
                node.setLHS((TreeNode(value, node)))
            else:  # 지정된 것이 있다면
                self.insert(value, node.getLHS())
 def deserialize(self, data):
     if data[0] == "[" or data[0] == "{":
         data = data[1:-1]
     data = data.split(",")
     if len(data) == 0 or data[0] == "": return None
     root = TreeNode(int(data[0]))
     queue = [root]
     i = 1
     while len(queue) > 0 and i < len(data):
         top = queue.pop(0)
         if data[i] != "null" and data[i] != "#":
             node = TreeNode(int(data[i]))
             queue.append(node)
         else:
             node = None
         top.left = node
         i += 1
         if len(data) == i: break
         if data[i] != "null" and data[i] != "#":
             node = TreeNode(int(data[i]))
             queue.append(node)
         else:
             node = None
         top.right = node
         i += 1
     return root
 def buildTreeFromTraverse(self, istart, iend, pstart, pend):
     if istart == iend or pstart == pend: return None
     root = TreeNode( self.postorder[pend-1] )
     for split in xrange(istart, iend):
         if self.inorder[split] == self.postorder[pend -1]: break
     root.left = self.buildTreeFromTraverse(istart, split, pstart, pstart+split-istart)
     root.right = self.buildTreeFromTraverse(split+1, iend, pstart+split-istart, pend-1)
     return root
예제 #19
0
 def constructMaximumBinaryTree2(self, nums):
     i = nums.index(max(nums))  # max val and index, this one better
     root = TreeNode(nums[i])
     if nums[:i]:
         root.left = self.constructMaximumBinaryTree2(nums[:i])
     if nums[i + 1:]:
         root.right = self.constructMaximumBinaryTree2(nums[i + 1:])
     return root
예제 #20
0
    def mergeTrees(self, t1, t2):
        if t1 is None and t2 is None:
            return None
        ans = TreeNode((t1.data if t1 else 0) + (t2.data if t2 else 0))
        ans.left = self.mergeTrees(t1 and t1.left, t2 and t2.left)
        ans.right = self.mergeTrees(t1 and t1.right, t2 and t2.right)

        return ans
def buildTree(preorder, inorder):
    if inorder == []:
        return None
    root = TreeNode(preorder[0])
    rootI = inorder.index(preorder[0])
    root.left = buildTree(preorder[1:1 + rootI], inorder[:rootI])
    root.right = buildTree(preorder[1 + rootI:], inorder[rootI + 1:])
    return root
 def buildTree(self, nums, left, right):
     if right == left:
         return None
     mid = (left + right) / 2
     root = TreeNode(nums[mid])
     root.left = self.buildTree(nums, left, mid)
     root.right = self.buildTree(nums, mid + 1, right)
     return root
예제 #23
0
 def bstFromPreorder_OJ(self, A, bound=float('inf')):
     # bound is the upper limit
     if self.i == len(A) or A[self.i] > bound:
         return None
     root = TreeNode(A[self.i])
     self.i += 1  # basic idea is to consume A[i] only if A[i] < bound
     root.left = self.bstFromPreorder_OJ(A, root.val)
     root.right = self.bstFromPreorder_OJ(A, bound)
     return root
예제 #24
0
 def helper():
     if a[self.i] == '#':
         self.i += 1
         return None
     root = TreeNode(int(a[self.i]))
     self.i += 1
     root.left = helper()
     root.right = helper()
     return root
 def buildTreeFromTraverse(self, preorder, pstart, pend, inorder, istart, iend):
     if istart == iend or pstart == pend: return None
     root = TreeNode(preorder[pstart])
     for rootidx in xrange(istart, iend):
         if preorder[pstart] == inorder[rootidx]:
             break
     root.left = self.buildTreeFromTraverse(preorder, pstart+1, pstart+1+rootidx-istart, inorder, istart, rootidx)
     root.right = self.buildTreeFromTraverse(preorder, pstart+1+rootidx-istart, pend, inorder, rootidx+1, iend)
     return root
예제 #26
0
def insert(root, val):
    if val < root.val and root.left == None:
        root.left = TreeNode(val)
    elif val >= root.val and root.right == None:
        root.right = TreeNode(val)
    elif val < root.val and root.left != None:
        return insert(root.left, val)
    elif val >= root.val and root.right != None:
        return insert(root.right, val)
예제 #27
0
def add_node(nodes, state, sample, parent, rwd):
    node = TreeNode(state, \
                    sample=sample, \
                    parent=parent, \
                    rwd=rwd)
    node.goal_node_flag = False
    node.pred_time = 0
    nodes += [node]
    return node
예제 #28
0
def build_tree(gains, root_node, dataframe, target):
    # print gains
    # print dataframe

    # the attribute with highest gain
    highest = highest_gain(gains)

    # all possible values for highest gain attribute
    vals = dataframe[highest].unique()

    # loop through each value
    for sj_val in vals:
        attrib = "%s=%s" % (highest, sj_val)

        # removes the highest gain from the gains dictionary
        new_gains = gains.copy()
        new_gains.pop(highest, None)


        # if for some reason the value isn't in the gains dictionary, just skip it
        if str(sj_val) not in gains[highest]:
            continue

        # if ent == 0, then it has a leaf node w/ tv as data
        # if not, then we add a new child node w/ value as branch
        if gains[highest][str(sj_val)]['ent'] == 0:
            leaf = tn.TreeNode(target, data=gains[highest][str(sj_val)]['tv'], entropy=gains[highest][str(sj_val)]['ent'],
                               splitAttrib=attrib)
            root_node.addChild(leaf)
        else:
            childnode = tn.TreeNode(target, entropy=gains[highest][str(sj_val)]['ent'],
                               splitAttrib=attrib)           # make a child for this attribute

            # make the subset
            subset_df = dataframe[dataframe[highest] == sj_val]

            # do a leaf node if there are no values in the subset otherwise add a child
            if len(subset_df) > 0:
                # removes the highest gain column
                subset_df.drop(highest, axis=1, inplace=True)
                # recalculuate the gains from this subset
                recalc_gains = calculate_gain(subset_df, target)
                # if we're down to the last non-target column in the subset, add a leaf node
                if len(subset_df.columns) > 1 and recalc_gains != 1.0:
                    root_node.addChild(build_tree(recalc_gains, childnode, subset_df, target))
                else:
                    leaf = tn.TreeNode(target, data=gains[highest][str(sj_val)]['tv'],
                                       entropy=gains[highest][str(sj_val)]['ent'],
                                       splitAttrib=attrib)
                    root_node.addChild(leaf)
            else:
                leaf = tn.TreeNode(target, data=gains[highest][str(sj_val)]['tv'],
                                   entropy=gains[highest][str(sj_val)]['ent'],
                                   splitAttrib=attrib)
                root_node.addChild(leaf)
    return root_node
 def helper(nums, start, end):
     if start > end:
         return None
     if start == end:
         return TreeNode(nums[start])
     mid = start + (end - start) // 2
     ret = TreeNode(nums[mid])
     ret.left = helper(nums, start, mid - 1)
     ret.right = helper(nums, mid + 1, end)
     return ret
예제 #30
0
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root == None:
            return
        temp = root.right
        root.right = root.left
        root.left = temp

        self.invertTree(root.left)
        self.invertTree(root.right)
        return root
예제 #31
0
 def build(self, l, r):
     if l > r:
         return None
     mid = l + (r - l) / 2
     left = self.build(l, mid - 1)
     root = TreeNode(self.cur.val)
     root.left = left
     self.cur = self.cur.next
     root.right = self.build(mid + 1, r)
     return root
예제 #32
0
    def sortedArrayToBST2(self, nums):
        if not nums:
            return None

        mid = len(nums) // 2
        root = TreeNode(nums[mid])
        root.left = self.sortedArrayToBST2(nums[:mid])
        root.right = self.sortedArrayToBST2(nums[mid + 1:])

        return root
예제 #33
0
    def helper(self, vals, l, r):
        if l == r:
            return TreeNode(vals[l])

        mid = r - (r - l) // 2
        n = TreeNode(vals[mid])
        n.left = self.helper(vals, l, mid - 1)
        if mid + 1 <= r:
            n.right = self.helper(vals, mid + 1, r)
        return n
 def _helper():
     if ix[0] == len(data):
         return
     if data[ix[0]] == '#':
         ix[0] += 1
         return
     root = TreeNode(data[ix[0]])
     ix[0] += 1
     root.left = _helper()
     root.right = _helper()
     return root
예제 #35
0
 def solution(self, nums, k, t):
     if not nums or len(nums) == 0:
         return False
     root = TreeNode(nums[0])
     root.state = 0
     n = len(nums)
     self.k = k
     self.t = t
     for i in range(1, n):
         num = nums[i]
         node = TreeNode(num)
         node.state = i
         if self.find(root, i, num - t, num + t):
             return True
         self.insert(root, node)
     return False
예제 #36
0
 def solve(self, n):
     if n < len(self.trees):
         return self.trees[n]
     result = []
     for left in xrange(0,n):
         right = n - 1 -left
         for leftnode in self.solve(left):
             for rightnode in self.solve(right):
                 root = TreeNode(left+1)
                 offset = left + 1
                 rightnode = self.fixAndCopyRightTree(rightnode, offset)
                 root.left = leftnode
                 root.right = rightnode
                 result.append(root)
     self.trees.append(result)
     return self.trees[n]
    def sortedListToBST(self, head):
        if not head:
            return head
        slow = head
        fast = head
        pre = None
        while fast.next and fast.next.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next

        if pre is not None:
            pre.next = None
        else:
            head = None
        root = TreeNode(slow.val)
        root.left = self.sortedListToBST(head)
        root.right = self.sortedListToBST(slow.next)
        return root
예제 #38
0
def create_tree(input_data):
    """
    Construction of a binary tree according to the formula and calculation
    values for the formula tasks in Reverse Polish Notation
    """

    # We use the list for temporary storage objects, which will be used as a stack
    stack = []

    for value in input_data.split():
        # If this operand create the object and place it in the stack
        try:
            value = int(value)
            stack.append(TreeNode(value))
        except ValueError:
            if value in ['+', '*', '-', '/']:
                # Take from the stack 2 last items when we get the operation and do calculation
                try:
                    node_right = stack.pop()
                    node_left = stack.pop()
                except IndexError:
                    raise IndexError("To many operands")

                if value == '+':
                    node_result = TreeNode(node_left.value+node_right.value)
                elif value == '-':
                    node_result = TreeNode(node_left.value-node_right.value)
                elif value == '*':
                    node_result = TreeNode(node_left.value*node_right.value)
                elif value == '/':
                    node_result = TreeNode(int(node_left.value/node_right.value))

                # Creation of the result object and initializing its connections
                node_result.init_node(node_left, node_right)
                stack.append(node_result)
            else:
                raise ValueError("Incorrect data value")

    # Check the state of the stack after a iterate over all data
    if len(stack) > 1:
        raise ValueError("We need more operators to evaluate the expression")
    elif len(stack) == 1:
        node_result = stack[-1]
    else:
        raise ValueError("Entry data is empty")

    return BinaryTree(node_result)
예제 #39
0
 def fixAndCopyRightTree(self, root, offset):
     if not root: return None
     newroot = TreeNode(root.val + offset)
     newroot.left = self.fixAndCopyRightTree(root.left, offset)
     newroot.right = self.fixAndCopyRightTree(root.right, offset)
     return newroot
import MySQLConnector as msc
from TreeNode import *

# Open database connection
db = MSdb.connect("128.199.212.227","flash","1q2w3e4r_","pcms_sim", charset='utf8' )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# set database connector
TreeNode.dbc = cursor

# select one id to be searched for
#sel_cid = 81
sel_cid = 82
node = TreeNode(sel_cid, cursor)

# get children
node.create_and_link_child_nodes()

# get parent
node.create_and_link_parent_node()


# disconnect from server
db.close()

# print tree
##node.print_tree()

if node.parent != None: