day137-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.
判断两棵二叉树是否完全相等

分析

用递归比较简单点。

题解

/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
// 递归
isSameTree (p, q) {
// 左右子树终止条件
if(p === null && q === null){
return true
}
// one null, other is not null, false
if(p !== null && q === null || p === null && q !== null){
return false
}
// val diff, false
if(p.val !== q.val){
return false
}
// find next level of tree
return isSameTree(p.right, q.right) && isSameTree(p.left, q.left)
}
文章作者: lmislm
文章链接: http://lmislm.com/2019/05/29/2019-05-29/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog