LeetCode Subtree of Another Tree

本文介绍了一种解决二叉树子树问题的方法,通过先序遍历找到所有可能的根节点,并逐一验证这些节点的子树是否与目标树完全相同。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

Example 1:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
Given tree t:
   4 
  / \
 1   2
Return true, because t has the same structure and node values with a subtree of s.

Example 2:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
    /
   0
Given tree t:
   4
  / \
 1   2

Return false.

题解:此题是给定两棵树,判断第二棵树是否为第一课二叉树的子树。我先写了一个方法用来判断给定的两棵二叉树是否相同,然后我又写了一个方法采用先序遍历,来得到第一棵二叉树中的那些和第二棵二叉树的根节点的值相同的所有节点,将它们保存在一个arraylist中,然后在主函数中,采用遍历此arraylist的方法,将每一次得到的节点和第二棵二叉树进行是否相同比较,直到遍历完这个arraylist,当然如果中途发现某个节点的子树和第二棵二叉树完全相同,那么就直接输出true;否则遍历完arraylist都没有发现子树,那么就直接输出false。

public class isSubtree
{
    public boolean isSubtree(TreeNode s,TreeNode t)
    {
        ArrayList<TreeNode> list = new ArrayList<>();
        if(s == null && t == null)
            return true;
        if(s != null && t == null)
            return false;
        if(s == null && t != null)
            return false;
        else
        {
            preOrder(s,t.val,list);
            int length = list.size();
            while(length-- > 0)
            {
                if(subtree(list.get(0),t) == true)
                    return true;
                else
                    list.remove(0);
            }
        }
        return false;

    }
    public boolean subtree(TreeNode s1,TreeNode s2)    //用来判断是否是相同的两棵二叉树
    {
        if(s1 == null && s2 == null)
            return true;
        if(s1 == null && s2 != null)
            return false;
        if(s1 != null && s2 == null)
            return false;
        if(s1.val == s2.val)
            return subtree(s1.left,s2.left) && subtree(s1.right,s2.right);
        else
            return false;
    }
    public void preOrder(TreeNode root,int target,ArrayList<TreeNode> list)   //采用先序遍历的方法来将第一棵二叉树中和第二棵二叉树的根节点的值相同的节点保存到一个arraylist中
    {
        if(root == null)
            return;
        if(root.val == target)
            list.add(root);
        preOrder(root.left,target,list);
        preOrder(root.right,target,list);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值