题目描述
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.
样例
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
思路分析
先序遍历,依次比较节点值即可
二叉树类的题,要注意递归方法的使用
代码
public boolean isSameTree(TreeNode p, TreeNode q) { if (p==null && q==null) { //都为空 即相等 return true; } if (p==null || q==null) { //任一为空 不满足条件 终止遍历 return false; } if (p.val == q.val) { //节点值对应相等 则比较左右子树的值 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); //递归实现遍历整个二叉树 } return false; }
结果