Simple Java iterative using two queue, 3ms


  • 0
    C
        public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> leftq = new LinkedList<TreeNode>();
        Queue<TreeNode> rightq = new LinkedList<TreeNode>();
        
        if(null == root || null == root.left && null == root.right) return true;
        leftq.add(root);
        rightq.add(root);
        while(leftq.size() != 0 && rightq.size() != 0){
        	TreeNode left = leftq.poll();
        	TreeNode right = rightq.poll();
        	if(null == left && null == right) continue;//if both null node.
        	if(null == left || null == right || left.val != right.val) return false;
        	leftq.add(left.left);
        	leftq.add(left.right);
        	
        	rightq.add(right.right);
        	rightq.add(right.left);
        }
        return leftq.size() == rightq.size();
    }

  • 0
    C

    I think I need to add parentheses in the first if sentence to make it clearer. Like below :

    if(null == root || (null == root.left && null == root.right)) return true;

  • -4
    C

    My recursive solution, only takes 1 ms.

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

    }


  • 0
    4

    Where is your breadthFirstSearch function?


  • 0
    C

    Sorry, I thought breadthFirstSearch is not a good method name because I thought I wasn't using breadth first search here, so I change it to symmetric. But I forgot to change all the method name.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.