zoukankan      html  css  js  c++  java
  • 100. Same Tree

    原文题目:

    Given two binary trees, write a function to check if they are equal or not.

    Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

    读题:

    给定两个二叉树,判断二叉树是否相等,判断条件是二叉树的结构一样并且各个节点的value也一样

    解题思路:

    有两个方法,递归和非递归,递归是采用DFS方法遍历二叉树,对每个节点和左右子树进行判断;非递归方法可以采用栈或者队列存储两棵树进行逐一比较

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    '''递归'''
    class Solution(object):
    	def isSameTree(self, p, q):
    		"""
    		:type p: TreeNode
    		:type q: TreeNode
    		:rtype: bool
    		"""
    		if p and q:
    			mid = p.val == q.val
    			l = self.isSameTree(p.left, q.left)
    			r = self.isSameTree(p.right, q.right)
    			return mid and l and r
    		return p == q
    
    
    '''非递归'''	
    class Solution(object):
    	def isSameTree(self, p, q):
    		"""
    		:type p: TreeNode
    		:type q: TreeNode
    		:rtype: bool
    		"""
    		stack = [(p, q)]
    		while stack:
    			p, q = stack.pop()
    			if not p and not q:
    				continue
    			if not p or not q:
    				return False
    			if p.val == q.val:
    				stack.append((p.right, q.right))
    				stack.append((p.left, q.left))
    			else:
    				return False
    		return True
    

      

  • 相关阅读:
    Myeclipse 10.7 android(安卓) 开发环境搭建
    matplotlib
    tophat cufflinks cuffcompare cuffmerge 的使用
    shell 随机从文件中抽取若干行
    liftover的使用/用法
    命令行运行R语言脚本(代码)
    R: NULL, NA, and NaN
    SOME USEFUL MACHINE LEARNING LIBRARIES.
    Flutter实战:手把手教你写Flutter Plugin
    Flutter学习笔记(五)
  • 原文地址:https://www.cnblogs.com/xqn2017/p/8006860.html
Copyright © 2011-2022 走看看