您的位置:首页 > 其它

leetcode专题—Subtree of Another Tree

2018-03-28 21:17 531 查看
原文:https://leetcode.com/problems/subtree-of-another-tree/description/
题目意思:判断两个二叉树种,是否存在,一个二叉树是另一二叉树的子树/**
* 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 (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);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: