原题链接:https://leetcode.com/problems/same-tree/
1. 题目介绍
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:
Example 2:
Example 3:
2. 解题思路
深度优先搜索 + 递归
DFS搜索,沿着深度优先搜索的方法,逐一遍历节点,如果遇到不相同的节点就返回false。
实现代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q != null){
return false;
}
if(p != null && q == null){
return false;
}
if(p == null && q == null){
return true;
}
if(p.val != q.val){
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right,q.right);
}
}