树的递归遍历,DFS遍历和BFS遍历

树的递归遍历,DFS遍历和BFS遍历

问题

https://leetcode.com/problems/same-tree/
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
在这里插入图片描述

解法一:递归遍历

class Solution:
    def isSameTree(self, p, q):
        if p and q:
            return p.val == q.val \
            and self.isSameTree(p.left, q.left) \
            and self.isSameTree(p.right, q.right)
        else:
            return p == q

解法二:DFS遍历

class Solution:
    def isSameTree_dfs(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        stack = [(p, q)]
        while stack:
            node1, node2 = stack.pop()
            if not node1 and not node2:
                continue
            elif None in [node1, node2]:
                return False
            else:
                if node1.val != node2.val:
                    return False
                stack.append((node1.right, node2.right))
                stack.append((node1.left, node2.left))
        return True

解法三:BFS遍历

class Solution:
    def isSameTree_bfs(self, p, q):
        queue = [(p, q)]
        while queue:
            node1, node2 = queue.pop(0)
            if not node1 and not node2:
                continue
            elif None in [node1, node2]:
                return False
            else:
                if node1.val != node2.val:
                    return False
                queue.append((node1.left, node2.left))
                queue.append((node1.right, node2.right))
        return True

总结

DFS模板

BFS模板

待续

猜你喜欢

转载自blog.csdn.net/JackComeOn/article/details/83041228