【LeetCode】 100. Same Tree 相同的树(Easy)(JAVA)

【LeetCode】 100. Same Tree 相同的树(Easy)(JAVA)

题目地址: https://leetcode.com/problems/same-tree/

题目描述:

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

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

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

题目大意

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

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

解题方法

毕竟是Easy的题目,适合二叉树入手,比较简单;只需要比较当前值是否相等,左右两边是否都是相等的二叉树即可,然后不断递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    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);
    }
}

执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 37.4 MB, 在所有 Java 提交中击败了 5.55% 的用户

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/105730993