• leetcode-572


    重开每日一题

    给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。

    示例 1:
    给定的树 s:

    3
    /
    4 5
    /
    1 2
    给定的树 t:

    4
    /
    1 2
    返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。

    示例 2:
    给定的树 s:

    3
    /
    4 5
    /
    1 2
    /
    0
    给定的树 t:

    4
    /
    1 2
    返回 false。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/subtree-of-another-tree
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    type TreeNode struct {
        Val int
        Left *TreeNode
        Right *TreeNode
    }
    
    func isSubtree(s *TreeNode, t *TreeNode) bool {
        if s == nil {
            return false
        }
        return check(s, t) || isSubtree(s.Left, t) || isSubtree(s.Right, t)
    }
    
    func check(a, b *TreeNode) bool {
        if a == nil && b == nil {
            return true
        }
        if a == nil || b == nil {
            return false
        }
        if a.Val == b.Val {
            return check(a.Left, b.Left) && check(a.Right, b.Right)
        }
        return false
    }

    简单的树递归深度遍历,不过性能较差。

    一个没有高级趣味的人。 email:hushui502@gmail.com
  • 相关阅读:
    First duplicate value
    SQL学习笔记day1
    Find closest value in BST
    BST construction
    Closest sum_pair
    滑动窗口 sliding window
    设计模式(3)观察者模式
    设计模式(1)装饰模式总结
    深刻探讨public class=new class();
    与时间赛跑,我的2012
  • 原文地址:https://www.cnblogs.com/CherryTab/p/12846547.html
Copyright © 2020-2023  润新知