[LeetCode每日一题]100. Same Tree
2020/2/20小于 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.
LeetCode-100 Same Tree 给定两个二叉树,让我们判断两棵二叉树是否完全相同。只需按序遍历每一个二叉树节点即可,判断节点的值是否相等,注意递归的返回条件即可。 代码如下:
/**
* 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) {
return q == null;
}
if (q == null) {
return p == null;
}
if (p.val != q.val) {
return false;
}
boolean left = isSameTree(p.left, q.left);
boolean right = isSameTree(p.right, q.right);
return left == true && right == true;
}
}
时间复杂度和空间复杂度均为O(n)。