lintcode 245. 子树

难度:简单

1. Description

image.png

2. Solution

原理:前序遍历相同的完全二叉树,是完全相同的二叉树。
把T1、T2按照完全二叉树来做前序遍历(空节点用'#'表示)。

  • python
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param T1: The roots of binary tree T1.
    @param T2: The roots of binary tree T2.
    @return: True if T2 is a subtree of T1, or false.
    """
    def pre_order(self, root, rst):
        if root is None:
            rst.append('#')
            return 
        rst.append(str(root.val))
        self.pre_order(root.left, rst)
        self.pre_order(root.right, rst)
        
    def isSubtree(self, T1, T2):
        # write your code here
        rst = []
        self.pre_order(T1, rst)
        po1 = ','.join(rst)
        
        rst = []
        self.pre_order(T2, rst)
        po2 = ','.join(rst)
        
        return po1.find(po2)!=-1

3. Reference

  1. (https://www.lintcode.com/problem/subtree/description?_from=ladder&&fromId=6)[https://www.lintcode.com/problem/subtree/description?_from=ladder&&fromId=6]
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容