问题描述:
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.
原问题链接:https://leetcode.com/problems/same-tree/
问题分析
这个问题相对比较简单,判断两棵树是否相等,主要判断这两棵树对应的每个节点是否都一致。比如说,当两个节点都是null的时候,它们应该是匹配的。同时如果两个节点都不为空的时候,它们需要判断当前两个节点的值是否相等以及递归的看它们的两个子节点。
于是我们就有了如下的代码实现:
/**
* 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 && p.val == q.val) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
return false;
}
}