Revertendo uma árvore binária em Java

Revertendo uma árvore binária em Java

1. Visão geral

Reversing a binary tree is one of the problems that we might be asked to solve during a technical interview.

Neste tutorial rápido, veremos algumas maneiras diferentes de resolver esse problema.

2. Árvore binária

A binary tree is a data structure in which each element has at most two children, que são referidos como o filho esquerdo e o filho direito. O elemento superior da árvore é o nó raiz, enquantothe children are the interior nodes.

No entanto,if a node has no child, it’s called a leaf.

Dito isso, vamos criar nosso objeto que representa um nó:

public class TreeNode {

    private int value;
    private TreeNode rightChild;
    private TreeNode leftChild;

    // Getters and setters

}

Então, vamos criar nossa árvore que usaremos em nossos exemplos:

    TreeNode leaf1 = new TreeNode(1);
    TreeNode leaf2 = new TreeNode(3);
    TreeNode leaf3 = new TreeNode(6);
    TreeNode leaf4 = new TreeNode(9);

    TreeNode nodeRight = new TreeNode(7, leaf3, leaf4);
    TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2);

    TreeNode root = new TreeNode(4, nodeLeft, nodeRight);

No método anterior, criamos a seguinte estrutura:

image

Invertendo a árvore da esquerda para a direita, acabaremos tendo a seguinte estrutura:

image

3. Revertendo a árvore binária

3.1. Método Recursivo

No primeiro exemplo,we’ll use recursion to reverse the tree.

Em primeiro lugar,we’ll call our method using the tree’s root, then we’ll apply it on the left and the right children respectively até chegarmos às folhas da árvore:

public void reverseRecursive(TreeNode treeNode) {
    if(treeNode == null) {
        return;
    }

    TreeNode temp = treeNode.getLeftChild();
    treeNode.setLeftChild(treeNode.getRightChild());
    treeNode.setRightChild(temp);

    reverseRecursive(treeNode.getLeftChild());
    reverseRecursive(treeNode.getRightChild());
}

3.2. Método Iterativo

No segundo exemplo,we’ll reverse the tree using an iterative approach. Para isso,we’re going to use a LinkedList, which we initialize with the root of our tree.

Então,for every node we poll from the list, we add its children to that list before we permutate them.

Continuamos adicionando e removendo deLinkedList até chegarmos às folhas da árvore:

public void reverseIterative(TreeNode treeNode) {
    List queue = new LinkedList<>();

    if(treeNode != null) {
        queue.add(treeNode);
    }

    while(!queue.isEmpty()) {
        TreeNode node = queue.poll();
        if(node.getLeftChild() != null){
            queue.add(node.getLeftChild());
        }
        if(node.getRightChild() != null){
            queue.add(node.getRightChild());
        }

        TreeNode temp = node.getLeftChild();
        node.setLeftChild(node.getRightChild());
        node.setRightChild(temp);
    }
}

4. Conclusão

Neste artigo rápido, exploramos as duas maneiras de reverter uma árvore binária. Começamos usando um método recursivo para revertê-lo. Então, acabamos usando uma maneira iterativa para alcançar o mesmo resultado.

O código-fonte completo desses exemplos e casos de teste de unidadecan be found over on Github.