二叉树交换方法

时间:2011-09-27 01:04:57

标签: java binary-tree swap

我在两个二叉树之间交换节点时遇到了麻烦。

我正在尝试将当前节点与树中传递的节点交换,但我无法弄清楚如何;我似乎只能交换节点的父节点,而不是交换节点本身。 谁能给我一些方向?

    public void swap(Node node) {           
        if(this.equals(this.parent.leftChild)){
            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

1 个答案:

答案 0 :(得分:0)

对于每个节点,节点都有对其父节点的引用,父节点具有对该子节点的引用。因此,如果您要交换两个节点,则需要更新四个引用。

Tree
  1  3
 /    \
2      4

所以这里......

  • 1有一个指向2的引用,指向4。
  • 2引用1应该指向3。
  • 4引用3应该指向1.
  • 3引用了4应该指向2。

希望有所帮助。