Click here to Skip to main content
15,891,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to print the keys at depth x in my BST.
Every source I have come across online has written a separate method outside of the main method to solve this problem. I also have a third class called MyTree that creates the BST.

Is it possible to do this all inside of the main method?


public class PrintDepth {
    private static int printdepth; // The depth to print all the elements.


    public static void main(String [] args) {
        MyTree T = new MyTree(); // Gets a Tree object.
        TreeNode root = T.getRoot(); // Gets the root of the tree.

        printdepth = 111; // sets the tree to depth 111. 


    }
}


public class TreeNode {
    public int key;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int _key, TreeNode l, TreeNode r) {
        key = _key;
        left = l;
        right = r;
    }
}


What I have tried:

The only thing I can even get to print is the root.
System.out.print(root.key);
Posted
Updated 5-Mar-20 8:47am
v2
Comments
Kris Lantz 5-Mar-20 14:20pm    
Why would you want to put all of that info into main only, and then recursively call main()? Splitting into methods is precisely the way I would do it. It makes things more manageable.
If you're referring to taking the separate classes and joining into a single, then that is possible.
guts716 5-Mar-20 14:40pm    
Okay that makes sense, I have been trying to use another method called printDistant and in the constructor it takes "TreeNode node" and an integer that holds the level of depth I want to print to. System.out.println(node.key); and printDistant(node.left, k - 1) do nothing. Can you provide some insight please?

I also have a third class called MyTree that creates the BST, I forgot to originally mention that. Its way too long to post I feel.
Kris Lantz 5-Mar-20 15:00pm    
Without knowing how the entire project functions, my insight is limited. The debugger would be useful here. Run through and see if the values are what you expect at each point, and go from there.
guts716 5-Mar-20 15:27pm    
Where can I find this debugger you speak of?
Kris Lantz 5-Mar-20 15:42pm    
What are you using to code in Java?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900