100 Same Tree

该博客讨论了LeetCode上的100号问题——判断两棵树是否相同。博主介绍了问题背景,指出问题的关键在于二叉树的遍历,并解释了三种遍历方式(前序、中序、后序)都可以用于解决这个问题。博主选择了使用前序遍历的方法,并提到当两节点都为空、一个为空另一个不空或节点值不同时,可以判断两棵树的不同。最后,博主分享了简洁的代码实现。
摘要由CSDN通过智能技术生成

题目链接:https://leetcode.com/problems/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.

解题思路:
这题是 easy ,考点是二叉树的遍历
比较两棵树是否相同,可以用前序,中序或后序遍历。
1. 当两个结点都为空时,说明两棵树在此都终结了。
2. 若一个为空,一个不为空,说明一棵树终结,另一棵还有结点,这两棵树就是不同的二叉树。
3. 当两个结点的值不同时,它们也是不同的二叉树。
很开心,这题和大神写的一样,采用前序遍历,代码十分简洁。

代码实现

/**
 * 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 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);
    }
}
54 / 54 test cases passed.
Status: Accepted
Runtime: 0 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值