572. Subtree of Another Tree

来源:互联网 发布:游戏租号 软件 编辑:程序博客网 时间:2024/06/06 15:17

1.题目

   

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 scould 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.

2.分析

   题意很明确,就是判断给定的两个二叉树,后者是不是前者的子树,当然树是自己的子树,树形结构本身就是递归定义,所以一般首先想到的解法就是递归调用。

3.解题

   我的解题:

public class Solution {    public boolean isSubtree(TreeNode one, TreeNode two) {        // 边界处理        Queue<TreeNode>s = new LinkedList<TreeNode>();        Queue<TreeNode>t = new LinkedList<TreeNode>();                if(one==null&&two==null){            return true;        }        if(one==null||two==null){            return false;        }        TreeNode a = one;        TreeNode b = two;        s.add(a);        t.add(b);        int flag = 0;                while(!s.isEmpty()&&!t.isEmpty()){            TreeNode tema = s.poll();            TreeNode temb = t.poll();            if(tema.val!=temb.val){                flag = 1;                break;            }            if(tema.left!=null){                s.add(tema.left);            }            if(tema.right!=null){                s.add(tema.right);            }            if(temb.left!=null){                t.add(temb.left);            }            if(temb.right!=null){                t.add(temb.right);            }        }        if(flag!=1 && s.isEmpty() && t.isEmpty()){            return true;        }        return (isSubtree(one.left,two)||isSubtree(one.right,two));    }}

其他人解题:

    

public class Solution {    public boolean isSubtree(TreeNode s, TreeNode t) {        if (s == null) return false;        if (isSame(s, t)) return true;        return isSubtree(s.left, t) || isSubtree(s.right, t);    }        private boolean isSame(TreeNode s, TreeNode t) {        if (s == null && t == null) return true;        if (s == null || t == null) return false;                if (s.val != t.val) return false;                return isSame(s.left, t.left) && isSame(s.right, t.right);    }}

4.总结

    其实我的思路和大多数思路差不多,就是递归调用,判断树是否相等,一直递归直到满足递归结束条件,结束递归,得出最后的结果,只是觉得别人写得代码好简洁,而且采用在方法中再次递归替代了我里面的辅助空间。所以时间效率我可能高点,但是空间开销要大一些。

原创粉丝点击