来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/same-tree/

描述

给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

题解

递归法

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public boolean isSameTree(TreeNode p, TreeNode q) {
  12. // p and q are both null
  13. if (p == null && q == null) return true;
  14. // one of q and q is null
  15. if (p == null || q == null) return false;
  16. if (p.val != q.val) return false;
  17. return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
  18. }
  19. }

复杂度分析

  • 时间复杂度 : 100. 相同的树(Same Tree) - 图1,其中100. 相同的树(Same Tree) - 图2是树的结点数,因为每个结点都访问一次。
  • 空间复杂度 : 最优情况(完全平衡二叉树)时为100. 相同的树(Same Tree) - 图3,最坏情况下(完全不平衡二叉树)时为100. 相同的树(Same Tree) - 图4,用于维护递归栈。