LintCode题解之子树_lintcode

 LintCode题解之子树_lintcode_02

 

思路: 最简单的方法,依次遍历比较就可以了。

 

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/

 

.