导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-100.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.

翻译

给出两颗二叉树,编写函数检查它们是否相等。
两颗二叉树相等的定义是它们的结构相同并且对应节点有相同的值。

遍历二叉树,当遇到节点时,首先非空判断,然后检查根的值,然后检查左右子树是否相等。
递归:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 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;

return (p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right));
}
}