leetcode100~Same Tree

本文介绍了一种用于检查两棵二叉树是否完全相同的算法,包括它们的结构和节点值。提供了两种实现方法:一种是递归方式,另一种是非递归方式使用栈来完成遍历。

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

该题比较简单,不作解释,不懂的话,欢迎提问~

public class IsSameTree {
    //递归实现
    public boolean isSameTree(TreeNode p,TreeNode q) {
        if(p==null && q==null) return true;
        if(p==null || q==null) return false;
        return (p.val==q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
    //非递归
    public boolean isSameTree2(TreeNode p,TreeNode q) {
        Stack<TreeNode> stack = new Stack<>();
        stack.push(p);
        stack.push(q);
        while(!stack.isEmpty()) {
            q=stack.pop();
            p=stack.pop();
            if(p==null && q==null) continue;
            if(p==null || q==null) return false;
            if(p.val!=q.val) return false;

            stack.push(p.left);
            stack.push(q.left);

            stack.push(p.right);
            stack.push(q.right);
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值