Leedcode相同二叉树 Python先序遍历

简介: Leedcode相同二叉树 Python先序遍历

问题描述:

image.png


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:return True
        if not p or not q:return False
        a=[]
        def pre_order(root):
            a.append(root.val)
            if root.left:
                pre_order(root.left)
            else:
                a.append(None)
            if root.right:
                pre_order(root.right)
            else:
                a.append(None)
            return a
        stack1=pre_order(p)
        a=[]
        stack2=pre_order(q)
        return True if stack1==stack2 else False


思路:就是用先序遍历的手段 效果还不错

image.png


我是小郑 期待与你一起进步😀


目录
相关文章
|
2月前
|
Python
【Leetcode刷题Python】236. 二叉树的最近公共祖先
LeetCode上236号问题"二叉树的最近公共祖先"的Python实现,使用递归方法找到两个指定节点的最近公共祖先。
35 5
|
2月前
|
存储 Python
【Leetcode刷题Python】103. 二叉树的锯齿形层序遍历
LeetCode上103号问题"二叉树的锯齿形层序遍历"的Python实现,使用了双端队列来实现层与层之间交替的遍历顺序。
17 3
|
2月前
|
Python
【Leetcode刷题Python】145. 二叉树的后序遍历
LeetCode上145号问题"二叉树的后序遍历"的Python实现方法。
20 2
|
2月前
|
Python
【Leetcode刷题Python】102. 二叉树的层序遍历
LeetCode上102号问题"二叉树的层序遍历"的两种Python实现方法:使用递归和使用双端队列。
20 2
|
2月前
|
Python
【Leetcode刷题Python】104. 二叉树的最大深度
LeetCode第104题"二叉树的最大深度"的Python语言解决方案,使用递归方法来计算给定二叉树的最大深度。
25 2
|
2月前
|
Python
【Leetcode刷题Python】144. 二叉树的前序遍历
LeetCode上144号问题"二叉树的前序遍历"的Python实现方法。
21 1
|
2月前
|
Python
【Leetcode刷题Python】105. 从前序与中序遍历序列构造二叉树
LeetCode上105号问题"从前序与中序遍历序列构造二叉树"的Python实现,通过递归方法根据前序和中序遍历序列重建二叉树。
20 3
|
2月前
|
Python
【Leetcode刷题Python】404. 左叶子之和
LeetCode第404题"左叶子之和"的Python解决方案,通过深度优先搜索(DFS)遍历二叉树,累加所有左叶子节点的值来求解。
22 1
|
2月前
|
Python
【Leetcode刷题Python】94. 二叉树的中序遍历
LeetCode上94号问题"二叉树的中序遍历"的Python实现方法。
14 0
|
5月前
|
算法 C++ Python
Python每日一练(20230425) 多数元素、二叉树层序遍历II、最接近的三数之和
Python每日一练(20230425) 多数元素、二叉树层序遍历II、最接近的三数之和
34 0
Python每日一练(20230425) 多数元素、二叉树层序遍历II、最接近的三数之和