Why does this "invert binary search tree" not work? It prints the correct output, but leetcode doesn't think so.


  • 0
    O
    public class Solution {
    public TreeNode invertTree(TreeNode root) {
        
        return invertBSTree(root);
        
    }
    
    public TreeNode invertBSTree(TreeNode root) {   // This is working for a BST, but apparently it is not wanted
        ArrayList<Integer> allNodes = new ArrayList<Integer>();
        
        traverse(root,allNodes);
        System.out.println("INPUT: " + allNodes.toString());
        
        int top = root.val;
        root = new TreeNode(top);
        
        for (Integer i : allNodes){
            int val = (int)i;
            if (val == top)
                continue;
            else {
                insert (root, val);
                System.out.println("insert: "+val);
            }
        }
        ArrayList<Integer> check = new ArrayList<Integer>();
        traverse(root,check);
        System.out.println("OUTPUT: " +check.toString());
        
        return root;
    }
    
    public void insert (TreeNode root, int a) {
        if (a > root.val) {
            if (root.left == null)
                root.left = new TreeNode(a);
            else 
                insert(root.left, a);
        } else {
            if (root.right == null)
                root.right = new TreeNode(a);
            else 
                insert(root.right, a);
        }
    }
    
    public void traverse (TreeNode root, ArrayList<Integer> list) {
        if (root == null)
            return;
        traverse(root.left, list);
        list.add(root.val);
        traverse(root.right, list);
    }
    }

  • 0
    J

    This problem wants to a method to invert the binary tree, not all of process including input, output.


Log in to reply
 

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