Árbol binario a string con paréntesis

Construya una string que consta de paréntesis y números enteros de un árbol binario con la forma transversal de preorden. 
El Node nulo debe representarse mediante un par de paréntesis vacíos «()». Omita todos los pares de paréntesis vacíos que no afectan la relación de mapeo uno a uno entre la string y el árbol binario original.

Ejemplos:  

C++

/* C++ program to construct string from binary tree*/
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer to left
   child and a pointer to right child */
struct Node {
    int data;
    Node *left, *right;
};
 
/* Helper function that allocates a new node */
Node* newNode(int data)
{
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
 
// Function to construct string from binary tree
void treeToString(Node* root, string& str)
{
    // bases case
    if (root == NULL)
        return;
 
    // push the root data as character
    str.push_back(root->data + '0');
 
    // if leaf node, then return
    if (!root->left && !root->right)
        return;
 
    // for left subtree
    str.push_back('(');
    treeToString(root->left, str);
    str.push_back(')');
 
    // only if right child is present to
    // avoid extra parenthesis
    if (root->right) {
        str.push_back('(');
        treeToString(root->right, str);
        str.push_back(')');
    }
}
 
// Driver Code
int main()
{
    /* Let us construct below tree
                1
               / \
              2   3
             / \   \
            4   5   6    */
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->right = newNode(6);
    string str = "";
    treeToString(root, str);
    cout << str;
}

Java

// Java program to construct string from binary tree
class GFG
{
     
/* A binary tree node has data, pointer to left
child and a pointer to right child */
static class Node
{
    int data;
    Node left, right;
};
static String str;
 
/* Helper function that allocates a new node */
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
 
// Function to construct string from binary tree
static void treeToString(Node root)
{
    // bases case
    if (root == null)
        return;
 
    // push the root data as character
    str += (Character.valueOf((char)
           (root.data + '0')));
 
    // if leaf node, then return
    if (root.left == null && root.right == null)
        return;
 
    // for left subtree
    str += ('(');
    treeToString(root.left);
    str += (')');
 
    // only if right child is present to
    // avoid extra parenthesis
    if (root.right != null)
    {
        str += ('(');
        treeToString(root.right);
        str += (')');
    }
}
 
// Driver Code
public static void main(String[] args)
{
     
    /* Let us construct below tree
             1
            / \
            2 3
            / \ \
            4 5 6 */
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.right = newNode(6);
    str = "";
    treeToString(root);
    System.out.println(str);
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 program to construct string from binary tree
 
# A binary tree node has data, pointer to left
# child and a pointer to right child
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to construct string from binary tree
def treeToString(root: Node, string: list):
 
    # base case
    if root is None:
        return
 
    # push the root data as character
    string.append(str(root.data))
 
    # if leaf node, then return
    if not root.left and not root.right:
        return
 
    # for left subtree
    string.append('(')
    treeToString(root.left, string)
    string.append(')')
 
    # only if right child is present to
    # avoid extra parenthesis
    if root.right:
        string.append('(')
        treeToString(root.right, string)
        string.append(')')
 
# Driver Code
if __name__ == "__main__":
 
    # Let us construct below tree
    #         1
    #     / \
    #     2     3
    #     / \     \
    # 4 5     6
 
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.right = Node(6)
    string = []
    treeToString(root, string)
    print(''.join(string))
 
# This code is contributed by
# sanjeev2552

C#

// C# program to construct string from binary tree
using System;
     
class GFG
{
     
/* A binary tree node has data, pointer to left
child and a pointer to right child */
public class Node
{
    public int data;
    public Node left, right;
};
static String str;
 
/* Helper function that allocates a new node */
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
 
// Function to construct string from binary tree
static void treeToString(Node root)
{
    // bases case
    if (root == null)
        return;
 
    // push the root data as character
    str += (char)(root.data + '0');
 
    // if leaf node, then return
    if (root.left == null && root.right == null)
        return;
 
    // for left subtree
    str += ('(');
    treeToString(root.left);
    str += (')');
 
    // only if right child is present to
    // avoid extra parenthesis
    if (root.right != null)
    {
        str += ('(');
        treeToString(root.right);
        str += (')');
    }
}
 
// Driver Code
public static void Main(String[] args)
{
     
    /* Let us construct below tree
            1
            / \
            2 3
            / \ \
            4 5 6 */
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.right = newNode(6);
    str = "";
    treeToString(root);
    Console.WriteLine(str);
}
}
 
// This code is contributed by Princi Singh

Javascript

<script>
 
    // JavaScript program to construct string from binary tree
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
 
    let str;
   
    /* Helper function that allocates a new node */
    function newNode(data)
    {
        let node = new Node(data);
        return (node);
    }
 
    // Function to construct string from binary tree
    function treeToString(root)
    {
        // bases case
        if (root == null)
            return;
 
        // push the root data as character
        str += String.fromCharCode(root.data + '0'.charCodeAt());
 
        // if leaf node, then return
        if (root.left == null && root.right == null)
            return;
 
        // for left subtree
        str += ('(');
        treeToString(root.left);
        str += (')');
 
        // only if right child is present to
        // avoid extra parenthesis
        if (root.right != null)
        {
            str += ('(');
            treeToString(root.right);
            str += (')');
        }
    }
     
    /* Let us construct below tree
             1
            / \
            2 3
            / \ \
            4 5 6 */
    let root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right.right = newNode(6);
    str = "";
    treeToString(root);
    document.write(str);
 
</script>

Publicación traducida automáticamente

Artículo escrito por chhavi saini 1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *