您的位置:首页 > 其它

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/

 

.

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