简体   繁体   中英

Java Binary Tree recursive Insert

I am new to Java. Please help me understand the below code, how the pointer is moving from left to right. This code is working perfectly. I just want to know the working.Lets say if we insert 20,30,10,35,9 .How pointer moves from 10 which is left of root 20 to 35 which is right of root 20, node 30 .Shouldn't it be always hanging to left and right of most recent node added as per the code.

    class Node {
    Node right, left;
    int data = 0;
    Node(int data) {
        this.data = data;
    }
    public void insert(int value) {
        if (value <= data) {
            if (left == null) {
                left = new Node(value);
            } else {
                left.insert(value);
            }
        } else {
            if (right == null) {
                right = new Node(value);
            } else {
                right.insert(value);
            }
        }
    }
}

The pointer moves correctly as the check if (value <= data) { decides which way to go, if the incoming value is less then or equal to the current node value then it will move to the left otherwise to the right. After the move it again calls insert over the left or right node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM