判断一个树是否为另一个树的子树

package search;

import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;

/*
* @author: wjf
* @version: 2016年4月22日 上午10:40:48
*/

public class Tree {

    public boolean check(TNode root1,TNode root2){
        if(root2==null){
            return true;
        }
        if(root1==null){
            return false;
        }
        if(root1.getValue() != root2.getValue()){
            return false;
        }else{
            return check(root1.getLeft(),root2.getLeft()) && check(root1.getRight(),root2.getRight());
        }
    }
    public boolean isPartTree(TNode root1,TNode root2){
        if(root2==null){
            return true;
        }
        if(root1==null){
            return false;
        }
        boolean result=false;
        if(root1.getValue() == root2.getValue()){
            result=check(root1,root2);
            if(result)return true;
        }
        if(!result){    
            result=isPartTree(root1.getLeft(),root2);
            if(!result){
                result=isPartTree(root1.getRight(),root2);
            }
            return result;
        }
        return false;
    }
    public static void main(String[] args){
        TNode root1=new TNode(1);
        TNode c1=new TNode(1);
        TNode c2=new TNode(2);
        TNode c3=new TNode(3);
        root1.setLeft(c1);
        c1.setRight(c2);
        c1.setLeft(c3);

        TNode root2=new TNode(1);
        TNode c4=new TNode(2);
        TNode c5=new TNode(3);
        root2.setLeft(c5);
        root2.setRight(c4);

        Tree tree=new Tree();

        System.out.println(tree.isPartTree(root1, root2));
        System.out.println(tree.isPartTree(null, c2));

    }

}
class TNode{
    private int value;
    private TNode left=null;
    private TNode right=null;
    public TNode(int value){
        this.value=value;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public TNode getLeft() {
        return left;
    }
    public void setLeft(TNode left) {
        this.left = left;
    }
    public TNode getRight() {
        return right;
    }
    public void setRight(TNode right) {
        this.right = right;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值