예제 #1
0
                res.append("->".join(path))
                path.pop()
                return
            if root.left:
                backtrack(root.left, res, path)

            if root.right:
                backtrack(root.right, res, path)
            path.pop()

        backtrack(root, res, [])
        return res


if __name__ == "__main__":

    tree = Tree()
    solution = Solution()
    while 1:
        str1 = input()
        if str1 != "":
            node_list = [num for num in str1.split(",")]
            for node in node_list:
                tree.add(node)
            print(f"层次遍历:{tree.traverse(tree.root)}")

            res = solution.binaryTreePaths(tree.root)
            print(res)
        else:
            break
예제 #2
0
class Solution:
    def dfs(self, root):
        if not root:
            return [0, 0]
        l = self.dfs(root.left)
        r = self.dfs(root.right)
        return [max(l) + max(r), root.val + l[0] + r[0]]

    def rob(self, root):
        return max(self.dfs(root))


if __name__ == "__main__":

    tree = Tree()
    solution = Solution()
    while 1:
        str1 = input()
        if str1 != "":
            node_list = str1.split(",")
            for node in node_list:
                tree.add(int(node))

            print(f"层次遍历:{tree.traverse(tree.root)}")

            res = solution.rob(tree.root)
            print(res)
        else:
            break
예제 #3
0
        counts = []
        totals = []
        dfs(root,0)
        return [total / count for total, count in zip(totals, counts)]
        
if __name__ == "__main__":
    
    tree1 = Tree()
    tree2 = Tree()
    solution = Solution()
    while 1:
        str1 = input()
        if str1 != "":
            node_list1 = str1.split(",")
            for node in node_list1:
                tree1.add(node)

            print(f"层次遍历:{tree1.traverse(tree1.root)}")

            res = solution.averageOfLevels1(tree1.root)
            print(res)
        else:
            break
    






        
예제 #4
0
    def check(self, s, t):
        if not s and not t:
            return True
        if (not s and t) or (s and not t) or (s.val != t.val):
            return False
        return self.check(s.left, t.left) and self.check(s.right, t.right)


if __name__ == "__main__":

    solution = Solution()
    while 1:
        str1 = input()
        str2 = input()
        if str1 != "" and str2 != "":
            s_tree = Tree()
            t_tree = Tree()
            s_node_list = [int(num) for num in str1.split(",")]
            for node in s_node_list:
                s_tree.add(node)
            t_node_list = [int(num) for num in str2.split(",")]
            for node in t_node_list:
                t_tree.add(node)
            print(f"层次遍历:{s_tree.traverse(s_tree.root)}")
            print(f"层次遍历:{t_tree.traverse(t_tree.root)}")

            res = solution.isSubtree(s_tree.root, t_tree.root)
            print(res)
        else:
            break