LeetCode Subtree of Another Tree

来源:互联网 发布:软件系统的可靠性 编辑:程序博客网 时间:2024/05/22 01:50

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);    }}