leetcode题记:Same Tree

港控/mmm° 2022-05-18 05:57 250阅读 0赞

编程语言:JAVA

题目描述:

  1. Given two binary trees, write a function to check if they are the same or not.
  2. Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
  3. Example 1:
  4. Input:
  5. 1 1
  6. / \ / \
  7. 2 3 2 3
  8. [1,2,3], [1,2,3]
  9. Output: true
  10. Example 2:
  11. Input:
  12. 1 1
  13. / \
  14. 2 2
  15. [1,2], [1,null,2]
  16. Output: false
  17. Example 3:
  18. Input:
  19. 1 1
  20. / \ / \
  21. 2 1 1 2
  22. [1,2,1], [1,1,2]
  23. Output: false

提交反馈:

  1. 57 / 57 test cases passed.
  2. Status: Accepted
  3. Runtime: 3 ms
  4. Submitted: 3 minutes ago
  5. You are here!
  6. Your runtime beats 98.53 % of java submissions.

解题思路:

  1. 最开始的想法是遍历二叉树,然后存入StringBuffer中,比较两个字符串是否相同。
  2. 百度参考大神博客之后,发现这样的办法虽然也可以完成,但是太笨了。
  3. 直接用递归方法,结束条件为两颗树都为空或者其中一颗为空或者p.val不等于q.val;

代码:

  1. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
  2. class Solution {
  3. public boolean isSameTree(TreeNode p, TreeNode q) {
  4. if(p==null && q==null)
  5. return true;
  6. if(p==null || q==null)
  7. return false;
  8. if(p.val!=q.val)
  9. return false;
  10. return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
  11. }
  12. }

发表评论

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

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

相关阅读