Exemplo n.º 1
0
        if root is None:
            return

        # 有节点,标记该节点深度
        depth += 1
        # 该节点为叶子节点
        if root.left is None and root.right is None:
            # 更新最大深度
            self.depth = max(depth, self.depth)
            return
        if root.left:
            self._dfs(root.left, depth)
        if root.right:
            self._dfs(root.right, depth)

    def _maxDepth2(self, root):
        # DFS
        if root is None:
            return 0
        self._dfs(root, 0)
        return self.depth


if __name__ == '__main__':
    obj = Solution()
    while True:
        nums_str = input().strip().split()
        nodes = [int(n) if n != 'null' else None for n in nums_str]
        root = get_binary_tree(nodes)
        res = obj._maxDepth2(root)
        print(res)
Exemplo n.º 2
0
        """

        if root is None:
            return None
        # 1表示还没有弹出孩子,0表示已经弹出孩子,可以访问
        stack = [(1, root)]
        res = []
        while stack:
            state, node = stack.pop()
            if state == 1:
                stack.append((0, node))  # 访问完右子树后访问父节点
                if node.right:
                    stack.append((1, node.right))
                if node.left:
                    stack.append((1, node.left))
            else:
                res.append(node.val)
        return res

if __name__ == '__main__':
    obj = Solution()
    while True:
        node_list_str = input().strip().split()
        node_list = [int(v) if v != 'null' else None for v in node_list_str]
        root = get_binary_tree(node_list)
        res = obj.postorderTraversal(root)
        print(res)