题目
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.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
思路
这一题是一个简单的递归算法:如果两个树都为空,则返回true;如果一个空一个非空,则返回false;如果两个树的值不同,则返回false;如果相等,则递归比较两棵树的左右子树。
代码
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q == null) return true;
if((p == null && q != null ) || (p != null && q == null)) return false;
if(p.val == q.val) {
if((p.left == null && q.left != null) || (p.left != null && q.left == null)) return false;
if((p.right == null && q.right != null) || (p.right != null && q.right == null)) return false;
if(p.left == null && p.right == null) return true;
if(p.left != null && p.right == null) return isSameTree(p.left , q.left);
if(p.right != null && p.left == null) return isSameTree(p.right , q.right);
else{
return (isSameTree(p.left , q.left) && isSameTree(p.right , q.right));
}
}
return false;
}
}
转载请注明原文地址: https://ju.6miu.com/read-675612.html