Advertisement
korobushk

symmetricBt

May 13th, 2021
861
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode() {}
  8.  *     TreeNode(int val) { this.val = val; }
  9.  *     TreeNode(int val, TreeNode left, TreeNode right) {
  10.  *         this.val = val;
  11.  *         this.left = left;
  12.  *         this.right = right;
  13.  *     }
  14.  * }
  15.  */
  16. class Solution {
  17.    public boolean isSymmetric(TreeNode root) {
  18.            
  19.                
  20.        if (root == null) {
  21.             return true;
  22.         }
  23.      
  24.             return mirror(root.left,root.right); // check the tree
  25.                                                                
  26.                                                                     //       1
  27.     }                                                               //     /   \
  28.                                                                     //   2       2
  29.                                                                 //      /      
  30.                                                             //         3   4    4   3
  31.         public boolean mirror(TreeNode l, TreeNode r){          // l.l       ==       r.r
  32.                                                                 //       l.r == r.l  
  33.           if(l==null&&r==null){     // symmetric
  34.                   return true;
  35.           }else if(l!=null&&r!=null){
  36.                   return l.val==r.val && mirror(l.left,r.right)&&   //
  37.                     mirror(l.right,r.left);
  38.           }
  39.                
  40.                
  41.            return false;
  42.            
  43.                
  44.          
  45.         }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement