[LeetCode] 100. Same Tree

Given the roots of two binary trees p and q, 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:
Example 1
Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:
Example 2
Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:
Example 3
Input: p = [1,2,1], q = [1,1,2]
Output: false

Constraints:
The number of nodes in both trees is in the range [0, 100].
-104 <= Node.val <= 104

相同的树。

给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

思路

题意是给两个树,判断他们是否相同。有两种思路,bfs和dfs。bfs是按层遍历tree,将每层的node塞进queue然后弹出比较,需要注意塞进queue的顺序。此处我只实现了dfs的做法。

复杂度

时间O(n)
空间O(n)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 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;
}
if (p.val == q.val) {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
return false;
}
}

JavaScript实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
const isSameTree = function(p, q) {
// corner case
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}

// normal case
if (p.val == q.val) {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
return false;
};

相关题目

1
2
100. Same Tree
572. Subtree of Another Tree

[LeetCode] 100. Same Tree
https://shurui91.github.io/posts/493219564.html
Author
Aaron Liu
Posted on
January 7, 2020
Licensed under