Exemplo n.º 1
0
    def isSameTree3(self, p: TreeNode, q: TreeNode) -> bool:
        """
        iterative BFS
        :param p:
        :param q:
        :return:
        """
        queue = [(p, q)]
        while queue:
            p, q = queue.pop(0)
            if not p and not q:
                continue
            elif None in (p, q):
                return False
            else:
                if p.val != q.val:
                    return False
                queue.append((p.left, q.left))
                queue.append((p.right, q.right))
        return True


if __name__ == '__main__':
    n1 = [1, None, 2]
    n2 = [1, 2]
    bt1 = create_btree(n1)
    bt2 = create_btree(n2)
    s = Solution()
    print(s.isSameTree3(bt1, bt2))
Exemplo n.º 2
0
        level, queue, height = [], [root], 1
        while queue:
            for node in queue:
                if node.left:
                    level.append(node.left)
                if node.right:
                    level.append(node.right)
            if level:
                height += 1
            queue = level[:]
            level = []
        return height

    def maxDepth2(self, root: TreeNode) -> int:
        """
        recursive
        假设每个叶子节点的高度都是0,从叶子节点网上逐层+1得到父节点的高度
        :param root:
        :return:
        """
        if not root:
            return 0
        return 1 + max(self.maxDepth2(root.left), self.maxDepth2(root.right))


if __name__ == '__main__':
    nums = [3, 9, 20, None, None, 15, 7]
    bt = create_btree(nums)
    s = Solution()
    print(s.maxDepth2(bt))
Exemplo n.º 3
0
from DataStructure.BinaryTree import BinaryTree as TreeNode, create_btree


class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        def go_along_left_branch(node, stack):
            while node:
                stack.append(node)
                node = node.left

        stack = []
        ans = []
        while True:
            go_along_left_branch(root, stack)
            if not stack:
                break
            root = stack.pop()
            ans.append(root.val)
            root = root.right
        return ans


if __name__ == '__main__':
    nums = [1, None, 3, 2]
    bt = create_btree()