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:
Given tree t:
Return true,
because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
Given tree t:
Return false.
解题思路:使用二叉树的先序遍历的思想,对于s,检查以其中每个结点为根节点的子树是否与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); } }
相关文章推荐
- [LeetCode] Subtree of Another Tree 另一个树的子树
- LeetCode - 572 - Subtree of Another Tree
- 【LeetCode】Subtree of Another Tree 解题报告
- leetcode 572 Subtree of Another Tree
- [LeetCode] Subtree of Another Tree
- LeetCode@Tree_572_Subtree_of_Another_Tree
- LeetCode 572: Subtree of Another Tree
- LeetCode Subtree of Another Tree
- leetcode : subtree of another tree
- leetcode(572):Subtree of Another Tree
- leetcode专题—Subtree of Another Tree
- leetcode[Subtree of Another Tree]//待整理多种解法
- LeetCode 572 Subtree of Another Tree
- leetcode 572 Subtree of Another Tree
- LeetCode Subtree of Another Tree
- 【Leetcode-easy-572】Subtree of Another Tree
- Subtree of Another Tree
- Leetcode算法学习日志-572 Subtree of Another Tree
- Subtree of Another Tree:判断一棵树是否是另一棵树的子树
- ch4.7: given 2 huge Binary tree t1, t2(>1millon nodes), decide if one tree is subtree of another one