leetcode题记:Symmetric Tree

爱被打了一巴掌 2022-05-18 07:50 318阅读 0赞

编程语言:JAVA

题目描述:

  1. Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
  2. For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
  3. 1
  4. / \
  5. 2 2
  6. / \ / \
  7. 3 4 4 3
  8. But the following [1,2,2,null,3,null,3] is not:
  9. 1
  10. / \
  11. 2 2
  12. \ \
  13. 3 3
  14. Note:
  15. Bonus points if you could solve it both recursively and iteratively.

提交反馈:

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

解题思路:

  1. 题目判断树是否对称,借助上一道题【Same Tree】的思路,将根节点分成左右两个数,分别判断左右树是否对称。
  2. 判断结束条件为:当前节点都为空,返回true
  3. 当前节点只有一个为空,返回false
  4. 当前值不相等,返回false
  5. isSame(p.left,q.right) && isSame(p.right,q.left);
  6. 这类型题目最主要的还是掌握递归思想吧,掌握了递归思想,简单题目大多都是递归思想。

代码:

  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 isSymmetric(TreeNode root) {
  4. if(root == null){
  5. return true;
  6. }
  7. TreeNode p = root.left;
  8. TreeNode q = root.right;
  9. return isSame(p,q);
  10. }
  11. public boolean isSame(TreeNode p, TreeNode q){
  12. if(p == null && q == null){
  13. return true;
  14. }
  15. if(p == null || q == null){
  16. return false;
  17. }
  18. System.out.println(p.val + ":" + q.val);
  19. if(p.val != q.val){
  20. return false;
  21. }
  22. return isSame(p.left,q.right) && isSame(p.right,q.left);
  23. }
  24. }

发表评论

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

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

相关阅读