2011-11-24 79 views
-2

这是我的方法到目前为止它可能是错误的,但我需要在二叉树中插入一个节点。在二叉树中插入一个节点

public Node insert(Node node, int data) 
{ 
    if (root = null) 
    { 
     root = insert(data); 
    } 
    else if (data < node.data) 
    { 
     node.left = insert(data); 
    } 
    else if (data > node.data) 
    { 
     node.right = insert(data); 
    } 
} 

有帮助吗?我正在使用bluej

+3

_“这可能是错的”_不是一个好的问题描述。如果您有具体问题,请提问。如果您看到错误/异常(这很可能是这种情况),请将它们发布。谢谢。 –

+0

如何在二叉树中插入一个节点是我的问题 – Elliot678

回答

1

看看binary search tree上的维基百科页面。 (由于你的节点是有序的,你实际上正在实现一个二叉查找树)。

给出了每个常见操作 - 例如insertion - 。 Java代码甚至提供并解释。

0

我会做它:

public void insert(Node node, int data) 
{ 
    if (node == null) 
    { 
     node = new Node(data, null, null); // create a new leaf node with the data. 
    } 
    else if (data < node.data) 
    { 
     insert(node.left, data); 
    } 
    else if (data > node.data) 
    { 
     insert(node.right, data); 
    } 
} 

没有必要在我看来任何回报,因为你的树已经连接,该功能只会在正确的位置添加一个新的节点。请拨打:

insert(root, data);