来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/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) {// p and q are both nullif (p == null && q == null) return true;// one of q and q is nullif (p == null || q == null) return false;if (p.val != q.val) return false;return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);}}
复杂度分析
- 时间复杂度 :
,其中
是树的结点数,因为每个结点都访问一次。
- 空间复杂度 : 最优情况(完全平衡二叉树)时为
,最坏情况下(完全不平衡二叉树)时为
,用于维护递归栈。
