[LeetCode] 572. 另一个树的子树

一开始自己想的用if else 处理,好像根本不好写。。。。

看了评论的方法,用  ||  来处理

/**
 * 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 boolean isSubtree(TreeNode s, TreeNode t) {
        if(t==null) return true;
        if(s==null) return false;
        return isSubtree(s.left,t)||isSubtree(s.right,t)||isSameTree(s,t);
    }

    public boolean isSameTree(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 isSameTree(s.left,t.left)&&isSameTree(s.right,t.right);
    }
}

 

posted @ 2020-05-07 21:33  doyi  阅读(92)  评论(0编辑  收藏  举报