美文网首页
Subtree of Another Tree

Subtree of Another Tree

作者: 我知他风雨兼程途径日暮不赏 | 来源:发表于2020-05-08 22:02 被阅读0次

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subtree-of-another-tree

1.Title

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.

2. JAVA Answer

time complexity:O(N),space complexity:O(N)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void findTreeNodeByValue(TreeNode s,int val,List<TreeNode> ret){
        if(s.val==val){
            ret.add(s);
        }
        TreeNode res = null;
        if(s.left!=null){
            findTreeNodeByValue(s.left,val,ret);
        }
        if(s.right!=null){
            findTreeNodeByValue(s.right,val,ret);
        }
    }

    public boolean isEqualTree(TreeNode l,TreeNode r){
        if(l==null && r == null){
            return true;
        }
        if(l==null || r==null){
            return false;
        }
        if(l.val==r.val){
            return isEqualTree(l.left,r.left) && isEqualTree(l.right,r.right);
        }
        return false;
    }

    public boolean isSubtree(TreeNode s, TreeNode t) {
        if(t==null || s==null){
            return false;
        }
        // 匹配到s value为t.value的节点
        List<TreeNode> ev = new ArrayList<>();
        findTreeNodeByValue(s,t.val,ev);
        if(ev.size()==0){
            return false;
        }
        for(TreeNode tn: ev){
            if(isEqualTree(tn,t)){
                return true;
            }
        }
        return false;

    }
}

相关文章

网友评论

      本文标题:Subtree of Another Tree

      本文链接:https://www.haomeiwen.com/subject/onxaghtx.html