LeetCode 572. 【Java】572. Subtree of Another Tree
原题链接
简单
作者:
tt2767
,
2020-03-26 16:25:46
,
所有人可见
,
阅读 673
/**
1. 遍历s的所有节点, 将每个节点与t比较, 完全一致返回true
*/
/**
* 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 (isSameTree(s, t)) return true;
if (s != null) return isSubtree(s.left, t) || isSubtree(s.right, t);
return false;
}
public boolean isSameTree(TreeNode s, TreeNode t){
if (s == null || t == null) return s == null && t == null ;
return s.val == t.val && isSameTree(s.left, t.left) && isSameTree(s.right, t.right);
}
}