Non-recursive solutions in Java - 3ms


  • 0
    H
    public boolean isSymmetric(TreeNode root) {
            ArrayList<TreeNode> pList = new ArrayList<TreeNode>(), cList = new ArrayList<TreeNode>();
    		if(root != null)
    			pList.add(root);
    		while(pList.size() > 0){
    			for(TreeNode node : pList){
    				if(node != null){
    					cList.add(node.left);
    					cList.add(node.right);
    				}
    			}
    			boolean match = true;
    			TreeNode n1, n2;
    			//cList.size must be an even
    			for(int i = 0; i < cList.size() / 2; i++){
    				n1 = cList.get(i);
    				n2 = cList.get(cList.size() - 1 - i);
    				if(n1 != null && n2 != null){
    					if(n1.val != n2.val){
    						match = false;
    						break;
    					}
    				}else if(n1 == null && n2 == null){
    					
    				}else{
    					match = false;
    					break;
    				}
    			}
    			if(!match)
    				return false;
    			pList = cList;
    			cList = new ArrayList<TreeNode>();
    		}
    		return true;
        }
    

Log in to reply
 

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