[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:
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2:
Input: p = [1,2], q = [1,null,2]
Output: false
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 |
|
JavaScript实现
1 |
|
相关题目
1 |
|
[LeetCode] 100. Same Tree
https://shurui91.github.io/posts/493219564.html