算法刷题第三天 叶子相似的树

叶子相似的树

题目要求

算法刷题第三天 叶子相似的树_第1张图片

解题思路

递归 & 迭代

代码

迭代

# 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 leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
        def dfs_NLR(root:TreeNode, res:List[int]):
            if root == None:
                return 
            if root.left ==None and root.right ==None:
                res.append(root.val)
            dfs_NLR(root.left,res)
            dfs_NLR(root.right,res)
        res1=[]
        dfs_NLR(root1,res1)
        res2=[]
        dfs_NLR(root2,res2)
        return res1 == res2

迭代

# 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 leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
        res1 = self.NLR(root1)
        res2 = self.NLR(root2)
        return res1 == res2
    def NLR(self,root:TreeNode):
        res=[]
        if root == None:
            return res
        stk = []
        p = root
        while p or stk:
            if p:
                if p.left ==None and p.right == None:
                    res.append(p.val)
                stk.append(p)
                p =p.left
            else:
                p = stk.pop(-1)
                p = p.right
        return res

复杂度分析

时间复杂度: O ( N ) O(N) O(N)
空间复杂度: O ( 1 ) O(1) O(1)

你可能感兴趣的:(算法,深度优先)