问题描述
Given two binary trees, 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.
思路
两个树都为空 相同 返回真,
两个树都不为空,结点值相等,左右子树都相同(递归判断)都满足则相同,否则不同
java实现
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) //两个都为空 相同 返回真
return true;
boolean result= p != null && q != null && p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);//两个树都不为空,结点值相等,左右子树都相同(递归判断)都满足则相同,否则不同
return result;
}
}