• 树的遍历 | 相同的树


    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.

    Example 1:
    
    Input:     1         1
              /        / 
             2   3     2   3
    
            [1,2,3],   [1,2,3]
    
    Output: true
    Example 2:
    
    Input:     1         1
              /           
             2             2
    
            [1,2],     [1,null,2]
    
    Output: false
    Example 3:
    
    Input:     1         1
              /        / 
             2   1     1   2
    
            [1,2,1],   [1,1,2]
    
    Output: false
    

    思路1:递归

    对于任何两棵相同的树,根节点值相同,且两个左右子树也相同。故我们只需要递归判断p的左子树和q的左子树是否相等,p的右子树和q的右子树是否相等,递归的退出条件为p与q均等于null或其中之一为null

    class Solution(object):
        def isSameTree(self, p, q):
            if p is None and q is None:
                return True
            elif p is not None and q is not None:
                return p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
            else:
                return False
    

    思路2: 迭代遍历

    对于两棵相同的树,我们在遍历的时候把其当做完全二叉树进行遍历,对于空节点,用#号替代,遍历的结果是相同的。

    class Solution(object):
        def isSameTree(self, p, q):
            p = self.pre_trival(p)
            q = self.pre_trival(q)
            return p == q
    
        def pre_trival(self,p):
            queue = [p]
            result = []
            while len(queue):
                p = queue.pop(0)
                if p:
                    result.append(p.val)
                    if p.left
                    queue.append(p.left)
                    queue.append(p.right)
                else:
                    result.append("#")
            return result
    
        def post_trival(self, p):
            if p:
                p.status = 1
            stack = [p]
            result = []
            while len(stack):
                    while p:
                        p =p.left
                        if p:
                            p.status = 1
                        stack.append(p)
                    p = stack.pop(-1)
                    if p and p.status == 1:
                        right = p.right
                        p.status = 0
                        stack.append(p)
                        if right:
                            right.status = 1
                        stack.append(right)
                    elif p  is None:
                        result.append("#")
                    else:
                        result.append(p.val)
                return result                 
    
  • 相关阅读:
    SQL Server逻辑读、预读和物理读
    SQL Server 视图
    SQL Server存储机制
    SQLServer
    数据库配置问题整理贴
    分析存储过程重编译的起因以及避免
    存储过程重编译的优点、缺点、确定引发语句
    查询反模式
    查询反模式
    状压DP的总结
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/10380928.html
Copyright © 2020-2023  润新知