【leetcode】100. Same Tree【java】

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.

中文:给定两颗二叉树,写一个函数判断这两棵树是否相等。如果两棵树的结构和各节点中保存的值是相等的,则认为这两棵树相等。

递归和非递归两种方法

代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //方法一:递归
        /*
        if (p == null || q == null){
            return p == q;
        }
        if (p.val != q.val){
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
        */
        //方法二:非递归
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();
        stack1.push(p);
        stack2.push(q);
        while(!stack1.isEmpty() && !stack2.isEmpty()){
            TreeNode n1 = stack1.pop();
            TreeNode n2 = stack2.pop();
            if (n1 == null && n2 == null){
                continue;
            }
            if (n1 == null || n2 == null || n1.val != n2.val){
                return false;
            }
            stack1.push(n1.left);
            stack2.push(n2.left);
            stack1.push(n1.right);
            stack2.push(n2.right);
        }
        return true;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值