二叉树,在特定的现有节点上添加节点

时间:2016-12-02 14:37:20

标签: java algorithm tree binary-tree

我试图用Java创建一个二叉树来模拟完美迷宫中的方式。

每个节点Node<T>可以有两个孩子(Node<T> leftNode<T> right)。 每个节点都以T data定义为(x,y)坐标。

要添加新节点,我需要找到实际节点(当前位置):

previousPosition = actualPosition; move(); tree.addNode(previousPosition, actualPosition);

addNode必须我搜索节点previousPosition,以便将子(actualPosition)添加到left或rigth(取决于null子)。

我需要你的帮助。

我的代码:

public class BinaryTree<T> {
    // Root node pointer. Will be null for an empty tree.
    private Node root;
    /*
--Node--
The binary tree is built using this nested node class.
Each node stores one data element, and has left and right
sub-tree pointer which may be null.
The node is a "dumb" nested class -- we just use it for
storage; it does not have any methods.
     */
    private static class Node<T> {
        Node<T> left;
        Node<T> right;
        T data;
        Node(T newData) {
            left = null;
            right = null;
            data = newData;
        }
    }
...
...
...
private Node<T> insert(Node<T> node, T parent, T data) {
        if(node.data.equals(parent)) {          
            if(node.left == null) {             
                node.left = new Node<T>(data);              
            } else if (node.right == null) {                
                node.right = new Node<T>(data);             
            } else {
                System.out.println("Children are not nulls");
            }

        } else {
            if(node.left != null) {
                insert(node.left, parent, data);                
            }
            if(node.right != null) {
                insert(node.right, parent, data);               
            }
        }       
        return node;
    }
}

0 个答案:

没有答案