Java, recursive and non-recursive solution, easy to understand


  • 0
    Y

    // Recursive solution, 1ms

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

    // Non-recursive solution, 2ms

    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root.right);
        stack.push(root.left);
        while (!stack.empty()){
            TreeNode left = stack.pop();
            TreeNode right = stack.pop();
            if (left == null && right == null) continue;
            if (left == null || right == null || left.val != right.val) return false;
            stack.push(right.left);
            stack.push(left.right);
            stack.push(right.right);
            stack.push(left.left);
        }
        return true;
    }

Log in to reply
 

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