コード例 #1
0
def main():
    solver = Solution()

    root = TreeNode(1)
    root.left = TreeNode(2)
    root.left.left = TreeNode(3)
    print(solver.maxPathSum(root))
コード例 #2
0
ファイル: merkle_tree.py プロジェクト: alan-lee/pysync
def _build_parent_node_list(directory, level, children):
    node_list = list()
    index = 0

    children.sort(key=lambda child_node: child_node.get_path())
    while index < len(children):
        if index % 2 != 0:
            node = TreeNode(directory + '_' + level + '_' + (index + 1) % 2)
            node.add_child(children[index])
            node.add_child(children[index - 1])

            if index == len(children) - 2:
                index += 1
                node.add_child(children[index])

            node.calc_signature()
            node_list.append(node)
        index += 1
    return node_list
コード例 #3
0
    while delta > 0 and node != None:
        node = node.parent
        delta -= 1
    return node


def depth(node):
    depth = 0
    while node != None and node.parent != None:
        node = node.parent
        depth += 1
    return depth


if __name__ == "__main__":
    n1 = TreeNode(1)
    n2 = TreeNode(2)
    n3 = TreeNode(3)
    n4 = TreeNode(4)
    n5 = TreeNode(5)
    n6 = TreeNode(6)
    ##
    n2.left = n1
    n2.right = n3
    n1.parent = n2
    n3.parent = n2
    ##
    n5.left = n4
    n5.right = n6
    n4.parent = n5
    n6.parent = n5
コード例 #4
0

class Solution:
    def __init__(self):
        self.res = 0

    def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
        if not root:
            return

        if root.val < L:
            self.rangeSumBST(root=root.right, L=L, R=R)
        elif root.val > R:
            self.rangeSumBST(root=root.left, L=L, R=R)
        else:
            self.res += root.val
            self.rangeSumBST(root=root.left, L=L, R=R)
            self.rangeSumBST(root=root.right, L=L, R=R)

        return self.res


if __name__ == '__main__':
    root: TreeNode = TreeNode(10)
    root.left: TreeNode = TreeNode(5)
    root.right: TreeNode = TreeNode(15)
    root.left.left: TreeNode = TreeNode(3)
    root.left.right: TreeNode = TreeNode(7)
    root.right.right: TreeNode = TreeNode(18)
    print(Solution().rangeSumBST(root=root, L=7, R=15))
コード例 #5
0
""" Code to test the bst_max() function

    Author: Russ Lewis
"""

import advanced_tree_funcs



###########################################################
#                       INPUT                             #
###########################################################

from tree_node import TreeNode

root = TreeNode(-31)
root.right = TreeNode(-19)
root.right.right = TreeNode(81)
root.right.right.left = TreeNode(-6)
root.right.right.left.right = TreeNode(77)
root.right.right.left.right.left = TreeNode(66)
root.right.right.left.right.left.left = TreeNode(52)
root.right.right.left.right.left.left.left = TreeNode(12)
root.right.right.left.right.left.left.left.right = TreeNode(50)


#vals = advanced_tree_funcs.in_order_vals(root)
#print(vals)
#print(sorted(vals))
#assert sorted(vals) == vals
コード例 #6
0
        # return rob and not_rob for this node
        return [rob, not_rob] #[rob, not_rob]

    return max(helper(root))

if __name__ == "__main__":
    # n1 = TreeNode(3)
    # n2 = TreeNode(2)
    # n3 = TreeNode(3)
    # n4 = TreeNode(3)
    # n5 = TreeNode(1)
    # n1.left = n2
    # n1.right = n3
    # n2.right = n4
    # n3.right = n5
    # print(rob(n1))

    n1 = TreeNode(3)
    n2 = TreeNode(4)
    n3 = TreeNode(5)
    n4 = TreeNode(1)
    n5 = TreeNode(3)
    n6 = TreeNode(10)
    n1.left = n2
    n1.right = n3
    n2.left = n4
    n2.right = n5
    n3.right = n6

    print(rob(n1))
コード例 #7
0
  1. Define post_order_traversal function.
  2. If the root is null, return an empty list.
  3. Get the list of values for visiting the left node.
  4. Get the list of values for visiting the right node.
  5. Return the left list values concatenated with the right list values,
     concatenated with the root value.
  """
    if root is None:
        return []

    left_values = post_order_traversal(root.left)
    right_values = post_order_traversal(root.right)
    return left_values + right_values + [root.value]


root = TreeNode('a')
b = TreeNode('b')
c = TreeNode('c')
d = TreeNode('d')
e = TreeNode('e')
f = TreeNode('f')

root.left = b
root.right = c
b.left = d
b.right = e
c.right = f

print(in_order_traversal())  # []
print(in_order_traversal(root))  # ['d', 'b', 'e', 'a', 'c', 'f']
print(post_order_traversal())  # []
コード例 #8
0
ファイル: merkle_tree.py プロジェクト: alan-lee/pysync
def _create_dir_node(dir_path, node_list):
    node = TreeNode(dir_path)
    for child_node in node_list:
        node.add_child(child_node)
    node.calc_signature()
    return node
コード例 #9
0
 def get_node_height(node: TreeNode):
     return TreeNode.get_height(node)
コード例 #10
0
 def inorder_traversal(self):
     return TreeNode.inorder_traversal(self._root, [])
コード例 #11
0
        t = stack.pop()
        # If any of the tree node is None, skip this iteration to pop next
        if t[0] == None or t[1] == None:
            continue
        # Both nodes are present, add them to first
        t[0].value += t[1].value
        ## LEFT CHILD
        # offload children to the stack
        if t[0].left == None:  # if t1's is child missing, attach t2's child
            t[0].left = t[1].left
        else:  # Push childs, Dont bother about t2's child if missing, just NOne to stack
            stack.append((t[0].left, t[1].left))
        ## RIGHT CHILD
        # offload children to the stack
        if t[0].right == None:  # if t1's is child missing, attach t2's child
            t[0].right = t[1].right
        else:  # Push childs, Dont bother about t2's child if missing, just NOne to stack
            stack.append((t[0].right, t[1].right))
    return t1


if __name__ == "__main__":
    n1 = TreeNode(1)
    n2 = TreeNode(2)
    n3 = TreeNode(3)
    n4 = TreeNode(4)
    n1.left = n2
    n1.right = n3
    merged_tree = mergeTrees(n1, n4)
    print(preorder(merged_tree))
コード例 #12
0
ファイル: main_story.py プロジェクト: mlburroughs/CYOA
class MainStory:
    """Defines the tree structure and executes interactive story."""
    def endings(total_moral_points, total_items):
        """Computes and prints ending based on items total (self.items_total)
        and moral points (self.moral_points).
        """

        total_ending = total_moral_points + total_items
        if total_ending >= 5:
            result = endings[0]
        elif total_ending <= 5 and total_ending > -5:
            result = endings[1]
        else:
            result = endings[2]
        print("Conclusion:" + "\n" + result + "\n" + "Moral Points: " +
              str(total_ending))

    story_root = TreeNode(texts[0], options[0])
    text2 = TreeNode(texts[1], options[1], mp[0])
    text3 = TreeNode(texts[2], options[2], mp[1])
    text4 = TreeNode(texts[3], options[3], mp[2])
    text5 = TreeNode(texts[4], options[4], mp[3])
    text6 = TreeNode(texts[5], options[5], mp[4])
    text7 = TreeNode(texts[6], options[6], mp[5])
    text8 = TreeNode(texts[7], story_items='judge hammer')
    text9 = TreeNode(texts[8], story_items='beads')
    text10 = TreeNode(texts[9])
    text11 = TreeNode(texts[10], story_items='axe trophy')
    text12 = TreeNode(texts[11], story_items='statue')
    text13 = TreeNode(texts[12])
    text14 = TreeNode(texts[13], story_items='silver spoon')
    text15 = TreeNode(texts[14])

    story_root.add_child(text2)
    story_root.add_child(text3)
    text2.add_child(text4)
    text2.add_child(text5)
    text3.add_child(text6)
    text3.add_child(text7)
    text4.add_child(text8)
    text4.add_child(text9)
    text5.add_child(text10)
    text5.add_child(text11)
    text6.add_child(text12)
    text6.add_child(text13)
    text7.add_child(text14)
    text7.add_child(text15)
    text8.add_child(text3)
    text9.add_child(text4)
    text11.add_child(text3)
    text13.add_child(text7)
    total_moral_points, total_items = story_root.traverse()

    endings(total_moral_points, total_items)
コード例 #13
0
    def build_tree(self, x_train: pd.DataFrame, y_train: np.array,
                   tree: TreeNode) -> None:
        """
        Build decision tree with ID3 feature choosing algorithm.

        :param x_train: Pandas data frame with the data (features) to train the model on. The array length is N*M where
                N is the number of samples in the dataset, and M is the number of features.
        :param y_train: Numpy array with the labels of the data. Length is N.
        :param tree: A root node.
        :return: None.
        """
        # Create new leaf with the class.
        if x_train.shape[0] == 1 or y_train.shape[
                0] <= self.pruning_M or self.are_all_labels_equal(y_train):
            new_node = TreeNode(self.find_major_class(y_train))
            tree.add_child(new_node)
            return

        # Find best feature to continue with, and best threhold to split the data with it.
        f_name, best_threshold = self.get_feature_with_max_info_gain(
            x_train, y_train)

        # Add another layer to the tree representing the current f, add thresh for prediction later.
        new_node = TreeNode((f_name, str(best_threshold)))
        tree.add_child(new_node)

        samples_great, labels_great, samples_small, labels_small = self.split_by_threshold(
            data=x_train, threshold=best_threshold, feature_name=f_name)
        if samples_great.shape[0] == 1:
            # If there is only one sample, no need to do recursion call.
            node = TreeNode(labels_great[0])
            new_node.add_child(node)
        else:
            self.build_tree(samples_great, labels_great, new_node)

        if samples_small.shape[0] == 1:
            # If there is only one sample, no need to do recursion call.
            node = TreeNode(labels_small[0])
            new_node.add_child(node)
        else:
            self.build_tree(samples_small, labels_small, new_node)

        return
コード例 #14
0
"""
from tree_node import TreeNode


class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        def get_root_length(root):
            if root:
                return 1 + max(get_root_length(root.left),
                               get_root_length(root.right))
            return 0

        def compute_length(root):
            if root:
                return max(
                    get_root_length(root.left) + get_root_length(root.right),
                    compute_length(root.left), compute_length(root.right))
            return 0

        if root:
            return compute_length(root)
        return 0


if __name__ == '__main__':
    tree = TreeNode(x=1)
    tree.left = TreeNode(x=2)
    tree.right = TreeNode(x=3)
    tree.left.left = TreeNode(x=4)
    tree.left.right = TreeNode(x=5)
    print(Solution().diameterOfBinaryTree(root=tree))
コード例 #15
0
 def _tree_generate(self, tree_node, train_data, depth):
     if train_data.shape[0] < self.min_samples_split \
             or train_data.shape[1] <= 2 \
             or self.max_depth is not None and depth == self.max_depth \
             or compute_gini(train_data['label']) < self.min_impurity_split:
         '''
         不再继续分裂的条件:
         当结点的样本数少于min_sample_split时
         当样本没有更多特征时
         当树的深度达到决策树的max_depth时
         当结点的样本集的Gini系数小于min_impurity_split时
         '''
         tree_node.type = 'leaf'
         tree_node.category = train_data['label'].value_counts(
             ascending=False).keys()[0]
         return
     # feature2values记录feature及其可能的取值
     feature2values = dict()
     for i in range(len(train_data.columns)):
         feature = train_data.columns[i]
         if feature != 'index' and feature != 'label' and pd.unique(
                 train_data[feature]).shape[0] > 1:
             feature2values[feature] = list(
                 train_data[feature].value_counts().keys())
     # 根据max_features选取特征
     chosen_features = list(feature2values.keys())
     chosen_features_num = len(chosen_features)
     if self.max_features == "log2":
         chosen_features_num = np.log2(len(chosen_features))
     elif self.max_features == "sqrt":
         chosen_features_num = np.sqrt(len(chosen_features))
     elif 0 < self.max_features < 1:
         chosen_features_num = len(chosen_features) * self.max_features
     chosen_features = np.random.choice(
         chosen_features, size=np.ceil(chosen_features_num).astype(int))
     # 枚举选取最优划分特征和特征值
     min_gini_index = 1
     split_feature = None
     split_feature_value = 0
     for feature in chosen_features:
         for value in feature2values[feature]:
             dv = train_data[train_data[feature] == value]
             dv_nums = dv.shape[0]
             gini_dv = compute_gini(dv['label'])
             dv_not = train_data[train_data[feature] != value]
             dv_not_nums = dv_not.shape[0]
             gini_dv_not = compute_gini(dv_not['label'])
             gini_index = (dv_nums * gini_dv + dv_not_nums *
                           gini_dv_not) / (dv_nums + dv_not_nums)
             if gini_index < min_gini_index:
                 min_gini_index = gini_index
                 split_feature = feature
                 split_feature_value = value
     # 划分样本集
     left_data = train_data[train_data[split_feature] ==
                            split_feature_value].drop([split_feature],
                                                      axis=1)
     right_data = train_data[
         train_data[split_feature] != split_feature_value]
     if pd.unique(right_data[split_feature]).shape[0] <= 1:
         right_data = right_data.drop([split_feature], axis=1)
     # 设置当前结点的属性
     tree_node.type = "internal"
     tree_node.split_feature = split_feature
     tree_node.split_feature_value = split_feature_value
     tree_node.left_node = TreeNode()
     tree_node.right_node = TreeNode()
     # 递归构建左右子结点
     self._tree_generate(tree_node=tree_node.left_node,
                         train_data=left_data,
                         depth=depth + 1)
     self._tree_generate(tree_node=tree_node.right_node,
                         train_data=right_data,
                         depth=depth + 1)
コード例 #16
0
    # root1.left = TreeNode(9)
    # root1.right = TreeNode(20)
    # root1.right.left = TreeNode(15)
    # root1.right.right = TreeNode(7)
    # print(Solution().verticalTraversal(root=root1))
    #
    # root2 = TreeNode(1)
    # root2.left = TreeNode(2)
    # root2.right = TreeNode(3)
    # root2.left.left = TreeNode(4)
    # root2.left.right = TreeNode(5)
    # root2.right.left = TreeNode(6)
    # root2.right.right = TreeNode(7)
    # print(Solution().verticalTraversal(root=root2))

    root3 = TreeNode(0)
    root3.left = TreeNode(8)
    root3.right = TreeNode(1)
    root3.right.left = TreeNode(3)
    root3.right.right = TreeNode(2)
    root3.right.left.right = TreeNode(4)
    root3.right.left.right.right = TreeNode(7)
    root3.right.right.left = TreeNode(5)
    root3.right.right.left.left = TreeNode(6)
    print(Solution().verticalTraversal(root=root3))

    # test_dict = {-1: 3, -2: 4}
    # sort_test_dict = list(test_dict.keys())
    # sort_test_dict.sort()
    # print(sort_test_dict)
# 可变对象与不可变对象, local vs global, 最好不用global
"""
def other_function(parameter):
    return parameter + 5

def main_function():
    x = 10
    print(x)    
    x = other_function(x)
    print(x)

a = 1
def f(x):
    x = 3

>>>f(a)
>>>a
1
"""

if __name__ == "__main__":
    root = TreeNode(10, TreeNode(6, 
                                    TreeNode(4),
                                    TreeNode(8)),
                        TreeNode(14, 
                                     TreeNode(12),
                                     TreeNode(16)))
    #root.print_tree()
    head = convert(root)
    print(head.val, head.right.val, head.right.left.val)
コード例 #18
0
 def get_tree_height(self) -> int:
     return TreeNode.get_height(self._root)
コード例 #19
0
def test():
    assert Solution().maxPathSum(TreeNode.from_list([-2, -1])) == -1
    assert Solution().maxPathSum(TreeNode.from_list([1, 2, 3])) == 6
    assert Solution().maxPathSum(
        TreeNode.from_list([-10, 9, 20, None, None, 15, 7])) == 42
コード例 #20
0
 def breadth_first_search(self):
     return TreeNode.breadth_first_search(self._root)
コード例 #21
0
ファイル: test-pre_order-3.py プロジェクト: Melifire/CS120
#! /usr/bin/python3
""" Code to test the pre_order_traversal_print() function

    Author: Russ Lewis
"""

import advanced_tree_funcs

###########################################################
#                       INPUT                             #
###########################################################

from tree_node import TreeNode

root = TreeNode(8)
root.left = TreeNode(-27)
root.left.left = TreeNode(41)
root.left.left.left = TreeNode(79)
root.left.left.left.left = TreeNode(-15)
root.left.left.right = TreeNode(-47)
root.left.right = TreeNode(21)
root.left.right.left = TreeNode(24)
root.left.right.left.left = TreeNode(54)
root.left.right.right = TreeNode(5)
root.right = TreeNode(-7)
root.right.left = TreeNode(-16)
root.right.left.left = TreeNode(64)
root.right.left.left.right = TreeNode(14)
root.right.left.left.right.left = TreeNode(85)
root.right.left.right = TreeNode(-25)
root.right.left.right.right = TreeNode(31)
コード例 #22
0
 def postorder_traversal(self):
     return TreeNode.postorder_traversal(self._root, [])
コード例 #23
0
#! /usr/bin/python3
""" Code to test the post_order_traversal_print() function

    Author: Russ Lewis
"""

import advanced_tree_funcs

###########################################################
#                       INPUT                             #
###########################################################

from tree_node import TreeNode

root = TreeNode(-19)
root.left = TreeNode(52)


###########################################################
#                     TEST CODE                           #
###########################################################
def main():
    print("Testing post_order_traversal_print()...")
    print()

    retval = advanced_tree_funcs.post_order_traversal_print(root)

    print(f"Returned value: {retval}")
    print()

    print("TESTCASE COMPLETED")
コード例 #24
0
        if A.left != None:
            q.put(A.left)
        if A.right != None:
            q.put(A.right)
        while not q.empty():
            current = q.get()
            if current != None:
                list.append(current.val)
                if current.left != None:
                    q.put(current.left)
                if current.right != None:
                    q.put(current.right)
        return list

s = Solution()
t1 = TreeNode(1)
t2 = TreeNode(2)
t3 = TreeNode(3)
t4 = TreeNode(4)
t5 = TreeNode(5)
t6 = TreeNode(6)
t7 = TreeNode(7)


t1.left = t2
t1.right = t3
t2.left = t4
t2.right = t5
t3.left = t6
t3.right = t7
コード例 #25
0
    return found


def general(root, node1, node2):
    """一般情形"""
    if find_node(root.left, node1):
        if find_node(root.right, node2):
            return root
        else:
            return general(root.left, node1, node2)

    else:
        if find_node(root.left, node2):
            return root
        else:
            return general(root.right, node1, node2)


if __name__ == "__main__":
    binary_search_tree = TreeNode(5, TreeNode(3, TreeNode(2), TreeNode(4)),
                                  TreeNode(7, TreeNode(6), TreeNode(8)))

    general_tree = TreeNode(1,
                            TreeNode(2, TreeNode(4), TreeNode(5, TreeNode(7))),
                            TreeNode(3, None, TreeNode(6)))

    print(BST(binary_search_tree, TreeNode(8), TreeNode(6)).val)
    print(find_node(general_tree, TreeNode(2)))
    print(general(general_tree, TreeNode(4), TreeNode(7)).val)
コード例 #26
0
ファイル: merkle_tree.py プロジェクト: alan-lee/pysync
def _create_file_node(file_path):
    node = TreeNode(file_path)
    node.calc_signature()
    return node
コード例 #27
0
ファイル: baseline.py プロジェクト: dlei/HiExpan
    seedEidsWithConfidence = [(child.eid, child.confidence_score)
                              for child in getNodesByLevel(rootNode, level)]
    newOrderedChildrenEidsWithConfidence = runSetExpan(seedEidsWithConfidence,
                                                       5**level)

    print(newOrderedChildrenEidsWithConfidence)
    for ele in newOrderedChildrenEidsWithConfidence:
        newChildEid = ele[0]
        confidence_score = ele[1]

        if level == 0:  # first level, just append them to root

            newChild = TreeNode(
                parent=rootNode,
                level=level,
                eid=newChildEid,
                ename=eid2ename[newChildEid],
                isUserProvided=False,
                confidence_score=confidence_score,
                max_children=level2max_children[targetNode.level + 1])
            rootNode.addChildren([newChild])

        else:
            # calculate best parent to attach to
            max_sim = 0
            best_parent = None
            for p in getNodesByLevel(rootNode, level -
                                     1):  # find all parents for this child
                #                 obtainReferenceEdges(rootNode.children[0])
                sim = sim_par_new(p.eid,
                                  ele[0],
                                  reference_edges,
コード例 #28
0
        node = queue.pop(0)
        node.left, node.right = node.right, node.left
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)
    return root


def preorder(root):
    return [root.value] + preorder(root.left) + preorder(
        root.right) if root else []


if __name__ == "__main__":
    n1 = TreeNode(4)
    n2 = TreeNode(2)
    n3 = TreeNode(7)
    n4 = TreeNode(1)
    n5 = TreeNode(3)
    n6 = TreeNode(6)
    n7 = TreeNode(9)
    n1.left = n2
    n1.right = n3
    n2.left = n4
    n2.right = n5
    n3.left = n6
    n3.right = n7
    print(preorder(n1))
    print(preorder(invertTree(n1)))
    print(preorder(invertTree(None)))
コード例 #29
0
 def put(self, key, val):
     if self.root:
         self._put(key, val, self.root)
     else:
         self.root = TreeNode(key, val)
     self.size = self.size + 1
コード例 #30
0
            return True
        else:
            return False

    def add_leaf(self, root: TreeNode, root_leaf: List):
        if root.left is None and root.right is None:
            root_leaf.append(root.val)
            return
        if root.left is not None:
            self.add_leaf(root.left, root_leaf=root_leaf)
        if root.right is not None:
            self.add_leaf(root.right, root_leaf=root_leaf)


if __name__ == '__main__':
    root1: TreeNode = TreeNode(1)
    root1.left = TreeNode(2)
    # root1: TreeNode = TreeNode(3)
    # root1.left = TreeNode(5)
    # root1.right = TreeNode(1)
    # root1.left.left = TreeNode(6)
    # root1.left.right = TreeNode(2)
    # root1.left.right.left = TreeNode(7)
    # root1.left.right.right = TreeNode(4)
    # root1.right.left = TreeNode(9)
    # root1.right.right = TreeNode(8)

    root2: TreeNode = TreeNode(2)
    root2.left = TreeNode(2)
    # root2.right = TreeNode(1)
    # root2.left.left = TreeNode(6)
コード例 #31
0
#! /usr/bin/python3
""" Code to test the post_order_traversal_print() function

    Author: Russ Lewis
"""

import advanced_tree_funcs

###########################################################
#                       INPUT                             #
###########################################################

from tree_node import TreeNode

root = TreeNode(-19)
root.left = TreeNode(52)
root.left.left = TreeNode(12)
root.left.left.left = TreeNode(66)
root.left.left.left.right = TreeNode(50)
root.left.left.right = TreeNode(-31)
root.left.left.right.right = TreeNode(81)
root.left.right = TreeNode(-6)
root.left.right.left = TreeNode(77)
root.left.right.right = TreeNode(34)
root.left.right.right.left = TreeNode(26)
root.right = TreeNode(-17)
root.right.left = TreeNode(-12)
root.right.left.left = TreeNode(40)
root.right.left.left.right = TreeNode(80)
root.right.left.left.right.left = TreeNode(4)
root.right.left.right = TreeNode(-25)
コード例 #32
0
ファイル: test-post_order-2.py プロジェクト: Melifire/CS120
""" Code to test the post_order_traversal_print() function

    Author: Russ Lewis
"""

import advanced_tree_funcs



###########################################################
#                       INPUT                             #
###########################################################

from tree_node import TreeNode

root = TreeNode(13)
root.left = TreeNode(26)
root.left.left = TreeNode(-11)
root.left.left.left = TreeNode(80)
root.left.left.left.right = TreeNode(-7)
root.left.left.left.right.right = TreeNode(-32)
root.left.left.right = TreeNode(85)
root.left.right = TreeNode(93)
root.left.right.left = TreeNode(52)
root.left.right.right = TreeNode(67)
root.left.right.right.left = TreeNode(81)
root.left.right.right.left.left = TreeNode(39)
root.left.right.right.left.right = TreeNode(32)
root.right = TreeNode(68)
root.right.left = TreeNode(75)
root.right.left.left = TreeNode(49)
コード例 #33
0
    def tree2str(self, t: TreeNode) -> str:
        if t:
            self.s = str(t.val)

            def helper(t):
                if not t.left and not t.right:
                    return
                if t.left:
                    self.s += '(' + str(t.left.val)
                    helper(t.left)
                    self.s += ')'
                else:
                    self.s += '()'
                if t.right:
                    self.s += '(' + str(t.right.val)
                    helper(t.right)
                    self.s += ')'

            helper(t)
            return self.s
        else:
            return ''


if __name__ == '__main__':
    root = TreeNode(x=1)
    root.left = TreeNode(x=2)
    root.right = TreeNode(x=3)
    root.left.left = TreeNode(x=4)
    print(Solution().tree2str(t=root))
コード例 #34
0
ファイル: avl_node.py プロジェクト: jaewie/algorithms
 def __init__(self, value):
     TreeNode.__init__(self, value)
     self.height = None
コード例 #35
0
def dfs_helper(root, optimal_res, inc=True):
    if root is None:
        return 0
    max_left = 0
    max_right = 0
    if root.left is not None and root.val - root.left.val == 1 and not inc:
        max_left = dfs_helper(root.left, optimal_res, not inc)
    elif root.left is not None and root.left.val - root.val == 1 and inc:
        max_left = dfs_helper(root.left, optimal_res, inc)
    else:
        dfs_helper(root.left, optimal_res, inc)
    if root.right is not None and root.val - root.right.val == 1 and not inc:
        max_right = dfs_helper(root.right, optimal_res, not inc)
    elif root.right is not None and root.right.val - root.val == 1 and inc:
        max_right = dfs_helper(root.right, optimal_res, inc)
    else:
        dfs_helper(root.right, optimal_res, inc)

    max_cur = 1 + max(max_left, max_right)
    optimal_res[0] = max(max_cur, optimal_res[0])
    return max_cur


if __name__ == '__main__':
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.left.left = TreeNode(3)
    root.left.right = TreeNode(3)
    root.left.right.left = TreeNode(4)
    print get_longest_consecutive_sequence(root)