Wednesday, October 22, 2014

Symmetric Tree LeetCode

Recursively:

public class Solution {
    public boolean isSymmetric(TreeNode root) {
       if (root == null) return true;
       return isSymmetric(root.left, root.right);
    }
   
    private boolean isSymmetric(TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        if (left == null || right == null) return false;
        if (left.val != right.val ) return false;
        return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }
   
}

Iteratively:

public boolean isSymmetric(TreeNode root) {
       if (root == null || root.left == null && root.right == null) return true;
     
       Queue<TreeNode> lq = new LinkedList<TreeNode>();
       Queue<TreeNode> rq = new LinkedList<TreeNode>();
       lq.add(root.left);
       rq.add(root.right);
       TreeNode leftTreeNode = null;
       TreeNode rightTreeNode = null;
     
       while (lq.isEmpty() == false && rq.isEmpty() == false) {
           leftTreeNode = lq.poll();
           rightTreeNode = rq.poll();
         
           if (leftTreeNode == null && rightTreeNode == null) {
               continue;
           }
           if ((leftTreeNode == null && rightTreeNode != null )|| (leftTreeNode != null && rightTreeNode == null)) {
               return false;
           }
           if (leftTreeNode.val != rightTreeNode.val) {
               return false;
           }
         
           lq.add(leftTreeNode.left);
           lq.add(leftTreeNode.right);
         
           rq.add(rightTreeNode.right);
           rq.add(rightTreeNode.left);
         
       }
       return (lq.isEmpty()&&rq.isEmpty());
    }

No comments:

Post a Comment