LintCode题解之子树
2017-11-22 02:16
260 查看
思路: 最简单的方法,依次遍历比较就可以了。
AC代码:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /* * @param T1: The roots of binary tree T1. * @param T2: The roots of binary tree T2. * @return: True if T2 is a subtree of T1, or false. */ public boolean isSubtree(TreeNode t1, TreeNode t2) { if(t2==null) return true; else if(t1==null) return false; else return isSame(t1, t2) || isSubtree(t1.left, t2) || isSubtree(t1.right, t2); } private boolean isSame(TreeNode t1, TreeNode t2){ if(t1==null || t2==null) return t1==t2; else return t1.val==t2.val && isSame(t1.left, t2.left) && isSame(t1.right, t2.right); } }
题目来源: http://www.lintcode.com/zh-cn/problem/subtree/
.
相关文章推荐
- Lintcode156 Merge Intervals solution 题解
- LintCode 数字组合 题解
- Lintcode136 Palindrome Partitioning solution 题解
- Lintcode141 Sqrtx solution 题解
- LintCode题解之比较字符串
- LintCode题解之斐波纳契数列
- LintCode题解之判断是否为平方数之和
- Lintcode 74 First Bad Version solution 题解
- Lintcode190 Next Permutation II solution 题解
- 剑指offer 面试题18: 树的子结构(LintCode 245.Subtree) 题解
- Lintcode155 Minimum Depth of Binary Tree solution 题解
- Lintcode183 Wood Cut solution 题解
- 【BZOJ】【P2729】【HNOI2012】【排队】【题解】【数学】
- P1019 单词接龙题解
- 合并两个排序链表 -lintcode
- 【BZOJ】【P3043】【IncDec Sequence】【题解】【差分】
- codevs 2833 奇怪的梦境 题解报告
- 今日头条2018春招-算法方向题解
- UVa102 Ecological Bin Packing(翻译+题解)
- 洛谷 1373 dp 小a和uim之大逃离 良心题解