LeetCode 572: Subtree of Another Tree

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 572: Subtree of Another Tree相关的知识,希望对你有一定的参考价值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if (s == null) {
            return false;
        }
        
        if (doesMatch(s, t)) {
            return true;
        }
        
        return isSubtree(s.left, t) || isSubtree(s.right, t);
    }
    
    private boolean doesMatch(TreeNode s, TreeNode t) {
        if (s == null && t == null) {
            return true;
        }
        
        if (s == null || t == null) {
            return false;
        }
        return s.val == t.val && doesMatch(s.left, t.left) && doesMatch(s.right, t.right);
    }
}

 

以上是关于LeetCode 572: Subtree of Another Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 572: Subtree of Another Tree

Leetcode 572. Subtree of Another Tree

leetcode572. Subtree of Another Tree

[LeetCode] 572. Subtree of Another Tree

[Leetcode] Binary tree-- 572. Subtree of Another Tree

LeetCode 572. 另一个树的子树(Subtree of Another Tree) 40