【Leetcode】Same Tree

本文介绍了一种用于判断两个二叉树是否相同的算法。通过递归或非递归方法检查二叉树的结构和节点值是否一致。提供了详细的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

题目要求:

给定两个二叉树,写一个函数来检查它们是否相投。

如果两个二叉树的结构相同并且结点有相同的值,我们就认为两个二叉树相同。

解题思路:

这类问题可以使用递归的方法来解决很简单,先检查结点是否同时为空,是则相同,否则不同,然后分别以左结点和右结点作为结点递归的调用自己,都相同则相同,否则不同。

Java :

非递归:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        LinkedList<TreeNode> t1 = new LinkedList<TreeNode>(); 
        LinkedList<TreeNode> t2 = new LinkedList<TreeNode>();
                        
        t1.add(p);
        t2.add(q);
        
        while(!t1.isEmpty() && !t2.isEmpty()){
            TreeNode c1 = t1.poll();
            TreeNode c2 = t2.poll();
            if(c1==null&&c2==null) continue;
            if(c1==null||c2==null) return false;
            if(c1.val!=c2.val) return false;
            
            t1.add(c1.left);
            t1.add(c1.right);
            t2.add(c2.left);
            t2.add(c2.right);
        }
        return true;
    }
}

递归是引用的:

http://blog.youkuaiyun.com/linhuanmars/article/details/22839819

public boolean isSameTree(TreeNode p, TreeNode q) {
    if(p==null && q==null)
        return true;
    if(p==null || q==null)
        return false;
    if(p.val!=q.val)
        return false;
    return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值