Java O(n) space DFS solution


  • 0
    Q
    public class Solution {
        public boolean isSymmetric(TreeNode root) {
            List<Integer> nodes1 = new ArrayList<Integer>();
            walkTree(root, nodes1, true);
            
            List<Integer> nodes2 = new ArrayList<Integer>();
            walkTree(root, nodes2, false);
            
            return nodes1.equals(nodes2);
        }
        private void walkTree(TreeNode n, List<Integer> list, boolean leftFirst){
            if (n!=null){
                list.add(n.val);
                if (leftFirst){
                    walkTree(n.left, list, leftFirst);
                    walkTree(n.right, list, leftFirst);
                }
                else{
                    walkTree(n.right, list, leftFirst);
                    walkTree(n.left, list, leftFirst);
                }
            }
            else{
                list.add(null);
            }
        }
    

    }


Log in to reply
 

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