Trees and Graphs Comments
Comments
-
It may be "better practice" to do that for the Nodes as well, but its simpler to do these algorithms without creating getters and setters for the Node's children.
-
Thanks!
-
I try to use this code https://www.learneroo.com/user_answers/7605767388
but I get back "Main.java:11: error: non-static variable this cannot be referenced from a static context Node node = new Node(ar[i]);"
I am going crazy. Where is the problem?
-
@Salvatore, looking briefly at your code, you should move your Node class out of the Main class (though you'll still have some more work to do).
public class Main{ //all of class Main } class Node{ //all of class Node }
-
Ops, thanks! Meanwhile I figured it out by myself.
And I am still fighting to find the solution. Keep (all of) you posted!
-
static class Node{
Node left;
Node right;
int key;Node(int key){ this.key = key; } } static void doStuff(int[] ar){ Node top = ar2SortedTree(ar);
printPreOrder(top); System.out.println(); } static void printPreOrder(Node curr){ if(curr == null) return; System.out.print(curr.key + " "); printPreOrder(curr.left); printPreOrder(curr.right); } static void insertKey(Node curr, int key){ if(key > curr.key){ if (curr.right != null){ insertKey(curr.right, key); } else { curr.right = new Node(key); } } else if(key < curr.key){ if (curr.left != null){ insertKey(curr.left, key); } else { curr.left = new Node(key); } } } static Node ar2SortedTree(int[] ar){ if(ar == null || ar.length == 0){ return null; } Node top = new Node(ar[0]); for(int i = 1; i < ar.length; i++){ insertKey(top, ar[i]); } return top; }
-
Why is "0 2 3 5 4 1" not a correct answer for input #1?
-
It's a valid BFS, but for this challenge you should visit nodes on one level in the order they were in their line of input.
-
That's not specified in the problem statement.
-
Thanks. It was mentioned previously, and I updated it so it's mentioned here as well.
Kendall Ponder
Jul 21, 3:47 PMIf it is best practice to make the node value private why isn't it best practice to make the children nodes private and require methods to access them?