Java stack-based iteration


  • 0
    S

    Standard tail-recursion => stack iteration conversion. Looks really simply though.

    public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        if(root.left == null && root.right != null) return false;
        if(root.right == null && root.left != null) return false;
        if(root.left == null && root.right == null) return true;
        if(root.left.val != root.right.val) return false;
        // return checkSym(root.left, root.right);
        /* use a stack for iteration. */
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.push(root.left);
        stack.push(root.right);
        while(!stack.isEmpty()) {
            TreeNode right = stack.pop();
            TreeNode left = stack.pop();
            if(left == null && right == null) continue;
            if(right == null || left == null) return false;
            if(left.val != right.val) return false;
            stack.push(left.left);
            stack.push(right.right);
            stack.push(left.right);
            stack.push(right.left);
        }
        
        return true;
    }
    
    public boolean checkSym(TreeNode left, TreeNode right) {
        if(left == null && right == null) return true;
        if(right == null || left == null) return false;
        if(left.val != right.val) return false;
        else return checkSym(left.left, right.right) && checkSym(left.right, right.left);
    }
    

    }


Log in to reply
 

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