binary tree swapping method
I'm having trouble with swapping nodes between two binary trees.
I'm trying to swap the current node with the passed node in the tree, but I can't figure out how; I can only seem to swap the parents of the nodes, but not the nodes themselves. Can anyone give me some direction?
public void swap(Node node) {
if(this.equals(this.parent.leftC开发者_如何转开发hild)){
Node tempNodeR = node.parent.rightChild;
System.out.println("Is a left child");
node.parent.rightChild = this.parent.leftChild;
this.parent.leftChild = tempNodeR;
}
else{
Node tempNodeL = node.parent.leftChild;
System.out.println("Is a right child");
node.parent.leftChild = this.parent.rightChild;
this.parent.rightChild = tempNodeL;
}
}
Calling node2.swap(node4):
Given Tree:
1 3
/ \
2 4
Resulting Tree (unchanged):
1 3
/ \
2 4
Expected Tree:
1 3
/ \
4 2
For each node, the node has a reference to its parent and the parent has a reference to that child. So if you're going to swap two nodes, you need to update four references.
Tree
1 3
/ \
2 4
So here...
- 1 has a reference that points to 2 that you want to point to 4.
- 2 has a reference to 1 that should point to 3.
- 4 has a reference to 3 that should point to 1.
- 3 has a reference to 4 that should point to 2.
Hope that helps.
精彩评论