题目链接:https://leetcode.com/problems/same-tree/
题目:
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.
解题思路:
这题是 easy ,考点是二叉树的遍历。
比较两棵树是否相同,可以用前序,中序或后序遍历。
1. 当两个结点都为空时,说明两棵树在此都终结了。
2. 若一个为空,一个不为空,说明一棵树终结,另一棵还有结点,这两棵树就是不同的二叉树。
3. 当两个结点的值不同时,它们也是不同的二叉树。
很开心,这题和大神写的一样,采用前序遍历,代码十分简洁。
代码实现
/**
* 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)
return false;
if(p.val != q.val)
return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
54 / 54 test cases passed.
Status: Accepted
Runtime: 0 ms