Ali second round of interviews: Handwriting Java binary tree

Ali Interview

Now many companies in the recruitment development positions, that they will indicate in advance the interviewer should have knowledge and skills in jobs, but also in the interview process, some skills for mastery of the strict requirements of the company will also require the interviewer handwriting Code, this link is the test of basic skills and strength interviewer!

This does not, the other day when a friend went to Ali's interview, in the course of two faces will be asked to use Java to achieve binary tree, the king Dog In the absence of this knowledge to prepare, did not answer it, and then let go home and informed .

So have the opportunity to take advantage of the king, Dog explain binary tree, I combed the whole common interview binary point at issue for everyone to exchange study. I want to help your interview.

Binary Tree

It is a recursive binary tree data structure, where each node can have up to two child nodes.

A common type of binary search tree is a binary tree, each node of which the value is greater than or equal to the value of the left child node, a node value and less than or equal to the right child node.

This is a visual representation of this binary tree:

For the implementation, we will use the Node class to store int value and saves a reference to each child node:

class Node {
    int value;//本节点的值
    Node left;//左边的子节点
    Node right;//右边的子节点
 
    Node(int value) {
        this.value = value;
        right = null;
        left = null;
    }
}

Then, let's add the root of the tree, commonly known as root :

public class BinaryTree {
 
    Node root;
 
    // ...
}

It is September and October quit quarter, as we collected a 2019 interview date information, there are documents, there are the Raiders, there is video. Needy students in public can be confidant number [Java], send [interview] to receive the latest information!

Let us work together to achieve lower

Now, let's look at the most common operations that can be performed on the binary tree What?

Insert elements

The first action we want to introduce new node is inserted .

First of all, we have to find where we want to add new nodes to the tree sort . We start from the root to follow these rules:

  • If the value of the new node is lower than the value of the current node, we go to the left child
  • If the value of the new node is greater than the value of the current node, we will go to the right child
  • The current node is null, we have reached a leaf node, we can insert a new node at this location

First, we will create a recursive method to insert:

private Node addRecursive(Node current, int value) {
    if (current == null) {
        return new Node(value);
    }
 
    if (value < current.value) {
        current.left = addRecursive(current.left, value);
    } else if (value > current.value) {
        current.right = addRecursive(current.right, value);
    } else {
        // value already exists
        return current;
    }
 
    return current;
}

Next, we will create a recursive method to create the root node:

public void add(int value) {
    root = addRecursive(root, value);
}

Now let's see how to use this method to create a tree from our example:

private BinaryTree createBinaryTree() {
    BinaryTree bt = new BinaryTree();
 
    bt.add(6);
    bt.add(4);
    bt.add(8);
    bt.add(3);
    bt.add(5);
    bt.add(7);
    bt.add(9);
 
    return bt;
}

Finding Elements

Now let's add a method to check whether the tree contains a specific value.

As before, we first create a recursive method to traverse the tree:

private boolean containsNodeRecursive(Node current, int value) {
    if (current == null) {
        return false;
    } 
    if (value == current.value) {
        return true;
    } 
    return value < current.value
      ? containsNodeRecursive(current.left, value)
      : containsNodeRecursive(current.right, value);
}

Here, we have to search for the value by comparing it with the value of the current node, and then continue to continue to look at the left or right child nodes according to the value.

Next, let us create a public method to find:

public boolean containsNode(int value) {
    return containsNodeRecursive(root, value);
}

Now, let's create a simple test to verify that tree really contain inserted elements:

@Test
public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() {
    BinaryTree bt = createBinaryTree();
 
    assertTrue(bt.containsNode(6));
    assertTrue(bt.containsNode(4));
  
    assertFalse(bt.containsNode(1));
}

Removing elements

Another common operation is to remove a node from the tree.

First, we must find the node to be removed in a similar manner to the previous:

private Node deleteRecursive(Node current, int value) {
    if (current == null) {
        return null;
    }
 
    if (value == current.value) {
        // Node to delete found
        // ... code to delete the node will go here
    } 
    if (value < current.value) {
        current.left = deleteRecursive(current.left, value);
        return current;
    }
    current.right = deleteRecursive(current.right, value);
    return current;
}

Once we find the node to be deleted, there are three main different situations:

  • Node has no children - this is the simplest case; we only need with its parent null replaces this node
  • Only one child node - in the parent node, we replace the node with its only child.
  • Node has two children - this is the most complicated case, because it requires tree reorganization

Let's see when the node is a leaf node of how we achieve the first case:

if (current.left == null && current.right == null) {
    return null;
}

Now let's continue the discussion node has a child node of the case:

if (current.right == null) {
    return current.left;
}
 
if (current.left == null) {
    return current.right;
}

Here we return a non-null child node, in order to assign it to the parent.

Finally, we must deal with the situation node has two child nodes.

First, we need to find a replacement node has been deleted. We will use the smallest node tree node to delete the right of the child:

private int findSmallestValue(Node root) {
    return root.left == null ? root.value : findSmallestValue(root.left);
}

We will then be assigned to the minimum value of the node you want to delete, and then we remove it from the right side of the sub-tree:

int smallestValue = findSmallestValue(current.right);
current.value = smallestValue;
current.right = deleteRecursive(current.right, smallestValue);
return current;

Finally, let us create a common method to remove:

public void delete(int value) {
    root = deleteRecursive(root, value);
}

Now, let's check delete is working as expected:

@Test
public void givenABinaryTree() {
    BinaryTree bt = createBinaryTree();
 
    assertTrue(bt.containsNode(9));
    bt.delete(9);
    assertFalse(bt.containsNode(9));
}

Conversion tree

Here, we will see a different way of traversing the tree, detailing the depth-first and breadth-first search.

We will use the same tree used before, and we will show the order of traversal of each case.

Depth-first search

Depth-first search is a brother as much as possible before a deep traversal in each child to explore.

There are several ways to do depth-first search: in-order, pre-order and post-order.

in-order: First, visit the left subtree, then visit the root, right subtree last visit:

public void traverseInOrder(Node node) {
    if (node != null) {
        traverseInOrder(node.left);
        System.out.print(" " + node.value);
        traverseInOrder(node.right);
    }
}

If we call this method, the console output:

3 4 5 6 7 8 9

pre-order: First, access the root node, then the left subtree, and finally the right subtree:

public void traversePreOrder(Node node) {
    if (node != null) {
        System.out.print(" " + node.value);
        traversePreOrder(node.left);
        traversePreOrder(node.right);
    }
}

If we call this method, the console output:

6 4 3 5 8 7 9

post-order: visit the left subtree, right subtree, root last visit:

public void traversePostOrder(Node node) {
    if (node != null) {
        traversePostOrder(node.left);
        traversePostOrder(node.right);
        System.out.print(" " + node.value);
    }
}

If we call this method, the console output:

3 5 4 7 9 8 6

BFS

This is another common type of traversing it in the show all the nodes access levels before entering the next level .

This is also referred to by level traversal order and start from the root, from left to right to access all levels of the tree.

For the implementation, we will use the queue in order to save each level node. We extract each node from the list, print its value, and then add its child nodes to the queue:

public void traverseLevelOrder() {
    if (root == null) {
        return;
    }
 
    Queue<Node> nodes = new LinkedList<>();
    nodes.add(root);
 
    while (!nodes.isEmpty()) {
 
        Node node = nodes.remove();
 
        System.out.print(" " + node.value);
 
        if (node.left != null) {
            nodes.add(node.left);
        }
 
        if (node.right!= null) {
            nodes.add(node.right);
        }
    }
}

In this case, the order of the nodes will be:

6 4 8 3 5 7 9

At last

In this article, we have learned how to implement a sorted binary tree and the most common operation in Java. Are you gain from it? Even if you can gain a little experience, in this small series also gratified!

"A short step, a thousand miles" in the hope that you can become the future: a dream horse habitat everywhere! Come on, Junior!


No public concern: "Java confidant" , updated daily Java knowledge Oh, look forward to your arrival!

  • Send " 1024 " to receive a free 30 classic programming books.
  • Send " Group ", progress with 100,000 programmers.
  • Send " interview " to receive information BATJ interview, video interview Raiders.
  • Send " JavaEE combat " receive "JavaEE combat" series of video tutorials.
  • Send " Fun algorithm " to receive "Fun algorithm" series of video tutorials.

Guess you like

Origin www.cnblogs.com/java-friend/p/11506106.html