245. Subtree【LintCode java】

Description

You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.

A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

Example

T2 is a subtree of T1 in the following case:

       1                3
      / \              /
T1 = 2   3      T2 =  4
        /
       4

T2 isn‘t a subtree of T1 in the following case:

       1               3
      / \               T1 = 2   3       T2 =    4
        /
       4解题:判断一个二叉树是不是另一个二叉树的问题。思路还是很清晰的,但是有些细节还是要注意下的。两个递归,一个用来判断两个树是否完全一样,这个只要不一样就返回false。还有一个递归函数是用来返回最终结果的。区别在于,如果第二个函数判断不等,还有继续往T2的子树探索,知道找到一个与T1完全相等的,或者一直到最后也不存在这样的函数。比较容易错的是,在判断结点值的时候,要先判断结点是不是null(判空)。代码如下:
/**
 * 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 equal(TreeNode T1, TreeNode T2){
        if(T1 == null && T2 == null){
            return true;
        }else if(T1 == null && T2 != null || T1 != null && T2 == null||T1.val != T2.val){
            return false;
        }else{
            return equal(T1.left, T2.left) && equal(T1.right, T2.right);
        }
    }
    public boolean isSubtree(TreeNode T1, TreeNode T2) {
        // write your code here
        if(T2 == null)
            return true;
        if(T1 == null)
            return false;
        if(equal(T1 , T2))
            return true;
        else return isSubtree(T1.left, T2)||isSubtree(T1.right, T2);
    }
}
 

原文地址:https://www.cnblogs.com/phdeblog/p/9300306.html

时间: 2024-08-30 03:52:01

245. Subtree【LintCode java】的相关文章

365. Count 1 in Binary【LintCode java】

Description Count how many 1 in binary representation of a 32-bit integer. Example Given 32, return 1 Given 5, return 2 Given 1023, return 9 Challenge If the integer is n bits with m 1 bits. Can you do it in O(m) time? 解题:很简单,但是要考虑范围的问题.代码如下: public

389. Valid Sudoku【LintCode java】

Description Determine whether a Sudoku is valid. The Sudoku board could be partially filled, where empty cells are filled with the character .. A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be vali

423. Valid Parentheses【LintCode java】

Description Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Example The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]"

【Effective Java】8、优先考虑类型安全的异构容器

有的时候我们一个容器只有一个类型或几个类型并不能满足我们的要求,比如set中存放的元素类型都是同一种,map也就指定的两种 这里我们可以将键进行参数化,而不是将容器参数化,也就是我们可以给容器传一个键的类型,然后value用来放对应的实例,这样就可以存放多个不同的类型了 如: package cn.xf.cp.ch02.item29; import java.util.HashMap; import java.util.Map; public class ManyTypeClass { //一个

【Effective Java】7、优先考虑泛型方法

package cn.xf.cp.ch02.item27; import java.util.HashSet; import java.util.Set; public class Union { /** * 这个方法就会有警告 * @param s1 * @param s2 * @return */ public static Set union1(Set s1, Set s2) { Set result = new HashSet(s1); result.addAll(s2); return

【Effective Java】5、覆盖equals时总要覆盖hashcode

package cn.xf.cp.ch02.item9; import java.util.HashMap; import java.util.Map; public class PhoneNumber { private final short areaCode; private final short prefix; private final short lineNumber; public PhoneNumber(int areaCode, int prefix, int lineNum

【Simple Java】HashMap常用方法

当需要对元素进行计数时,HashMap非常有用,如下例子,统计一个字符串中每个字符出现的次数: package simplejava; import java.util.HashMap; import java.util.Map.Entry; public class Q12 { public static void main(String[] args) { HashMap<Integer, Integer> countMap = new HashMap<Integer, Intege

【Simple Java】Java中怎样创建线程安全的方法

面试问题: 下面的方法是否线程安全?怎样让它成为线程安全的方法? class MyCounter { private static int counter = 0; public static int getCount() { return counter++; } } 本篇文章将解释一个常见的面试题,该问题被谷歌和很多其它公司问起过.它涉及的相对比较初级,而不是关于怎样去设计复杂的并发程序. 首先,这个问题的答案是No,因为counter++操作不是一个原子操作,而是由多个原子操作组成. 举个

【Effective Java】12、避免过度同步

这里有一个辅助基础类 package cn.xf.cp.ch02.item16; import java.util.Collection; import java.util.Iterator; import java.util.Set; public class ForwardingSet<E> implements Set<E> { /** * 这个类作为转发类,内部通过复合的方式把set作为一个组件 */ private final Set<E> s; public