您的位置:首页 > 其它

LeetCode: Subtree of Another Tree

2017-05-08 23:35 477 查看
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.

给两棵非空的二叉树s和t,检查二叉树t是否为s的子树(树t由树s中的一个结点及其所有子孙结点组成)

例如:

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.

解题思路:使用二叉树的先序遍历的思想,对于s,检查以其中每个结点为根节点的子树是否与t相同

代码如下:

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