1. 题目描述
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.
题目要求比较两棵二叉树是否完全相同。
2. 解题思路
采用一种递归的思想,树的深度优先遍历,同时访问两棵树的同一个节点,(1)比较节点值是否相同(2)访问他们的左孩子比较是否相同(3)访问他们的右孩子比较是否相同。当判定一个节点满足时需要同时满足以上三个条件,即该节点满足,该节点下的孩子们满足。
3. Code
/**
* 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;
}
// 判断两个节点是否只有一个节点为空
else if(p == null || q == null)
{
return false;
}
// 判断节点值是否相等
// 判断左边节点是否相等
// 判断右边节点是否相等
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}