Monday 15 June 2015

java - Setting the left attribute of a binary tree node through a for loop -


itemprop = "text">

I have a binary tree, which is being implemented through linked nodes (with: int element, binarronode left , Binary node correct, bien node parent attributes). And I want to set the nth node from the root, say, x if n = 3, so i want to root. Left.left.left.left = x

Initially, I was thinking of setting up a temporary BinaryNode variable and doing the following:

  BinaryNode temp = Route; BinaryNode x = new BinaryNode (10, empty, null, empty); For (int i = 0; i & lt; n; i ++) {temp = temp.left; }   

And then once I went to the end, I wanted to say, temp.left = x, but then I realized / did not do that to the actual tree would be nothing , Because there is only a copy of the temporary root?

So how would I go about trying to do this? : & Lt;

In your example, there is a copy of the temp root. This is the reference for the root, so your code will modify the original tree. However, you have another problem - what if the tree does not have nodes? In other words, if n is 5 and only three of the nodes are nodes, then you will get a NullPointerException . When you go down the chain, then you have to do a redundancy check.

No comments:

Post a Comment