zoukankan      html  css  js  c++  java
  • Leetcode算法刷题:第100题 Same Tree

    Same Tree

    题目

    给予两棵二叉树,判断这两棵树是否相等(即各节点的值都一样)

    解题思路

    分别遍历两棵二叉树,并用列表分别存储这两棵树的节点的值,比较这两个列表就可以了

    class Solution:
        # @param {TreeNode} p
        # @param {TreeNode} q
        # @return {boolean}
        def isSameTree(self, p, q):
            if (not p) and (not q):
                return True
            if (not p) and q:
                return False
            if (not q) and p:
                return False
            plist = self.pTree(p)
            qlist = self.qTree(q)
            if plist != qlist:
                return False
            return True
        
        def pTree(self, root):
            queue = []
            plist = []
            plist.append(root.val)
            queue.append(root)
            
            while queue:
                root = queue.pop(0)
    
                if root.left:
                    queue.append(root.left)
                    plist.append(root.left.val)
                if not root.left:
                    plist.append('null')
                if root.right:
                    queue.append(root.right)
                    plist.append(root.right.val)
                
                if not root.right:
                    plist.append('null')
    
            return plist
            
        def qTree(self, root):
            queue = []
            qlist = []
            qlist.append(root.val)
            queue.append(root)
            
            while queue:
                root = queue.pop(0)
    
                if root.left:
                    queue.append(root.left)
                    qlist.append(root.left.val)
                if not root.left:
                    qlist.append('null')
                if root.right:
                    queue.append(root.right)
                    qlist.append(root.right.val)
                if not root.right:
                    qlist.append('null')
    
            return qlist
    
  • 相关阅读:
    python2.7升python3.2
    SQL-基础学习使用的数据库资料
    SQL-基础学习2--ORDER BY ,DESC,WHERE, BETWEEN,AND ,OR ,IN ,NOT
    SQL-基础学习1--SELECT,LIMIT,DISTINCT,注释
    Python之Django-part 1
    python--文本处理1
    EXTJS4.2——8.Form+gride+linq进行前后端传输
    LINQ的实例
    高级委托使用
    C# 委托
  • 原文地址:https://www.cnblogs.com/eric-nirnava/p/leetcode-100.html
Copyright © 2011-2022 走看看