100. Same Tree

偏执的太偏执、 2022-03-08 16:50 239阅读 0赞

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.

  1. Example 1:
  2. Input: 1 1
  3. / \ / \
  4. 2 3 2 3
  5. [1,2,3], [1,2,3]
  6. Output: true
  7. Example 2:
  8. Input: 1 1
  9. / \
  10. 2 2
  11. [1,2], [1,null,2]
  12. Output: false
  13. Example 3:
  14. Input: 1 1
  15. / \ / \
  16. 2 1 1 2
  17. [1,2,1], [1,1,2]
  18. Output: false

难度:easy

题目:
给定两二叉树,写函数检查它们是否相同。
两个二叉树是否相同是由其结构和值都相同来决定。

思路:递归

  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. if (null == p && null != q || null != p && null == q) {
  13. return false;
  14. }
  15. if (null == p && null == q) {
  16. return true;
  17. }
  18. if (p.val != q.val) {
  19. return false;
  20. }
  21. return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
  22. }
  23. }

发表评论

表情:
评论列表 (有 0 条评论,239人围观)

还没有评论,来说两句吧...

相关阅读

    相关 #100 Same Tree

    按照通过率,第三的需要买书(还是过段时间再说吧……),那么就来做第四题咯 [\100 Same Tree][100 Same Tree] 这道题同样很简单,一看就是需