logo
Tags down

shadow

How to print binary tree in horizontal way?


By : SEGAProgrammer
Date : August 01 2020, 07:00 AM
Hope this helps You could create a hash map to indicate the level of the tree you are at in association with the values at that level of the tree. For example:
code :
std::map<unsigned, std::vector<unsigned>> hash;
hash[0] = { 5 };
hash[1] = { 2, 9 };
hash[2] = { 0, 3, 7, 12 };
for (unsigned i = 0; i < hash.size(); i++ ) { // each level of tree
    for (auto& v : hash[i] ) { // each element in that vector
        std::cout << v << " ";
    }
    std::cout << '\n';
}


Share : facebook icon twitter icon

Binary Tree : Non recursive routine to print ancestor of a node in a Binary Tree?


By : dinomite59
Date : March 29 2020, 07:55 AM
Hope that helps Use a non recursive sub routine to traverse the binary tree( refer to http://en.wikipedia.org/wiki/Tree_traversal#Implementations) and maintain a stack to store the all parent nodes in that array and whenever you pop from stack suitably pop the element from the stack. Finally when you find the element, second topmost element on the stack would be the ancestor.

construct and print elements of a Binary Tree (unbalanced binary tree), from left to right, and from bottom-up


By : Shahaan
Date : March 29 2020, 07:55 AM
this one helps. Here is an example of an unbalanced binary tree using C++. The data carried in each node is just a simple integer value (along with the management data of left and right child pointers and a depth for the level of the node).
Hopefully this shows how an insert visits nodes in the tree until it finds the proper place to insert a new node into the tree.
code :
// tree_data.cpp : Defines the entry point for the console application.
//

// VS2005 standard include for precompiled headers, etc.
#include "stdafx.h"

// C++ iostream header for standard output in namespace std::
#include <iostream>

// An unbalanced, ordered binary tree
// Left subtree are items less than the node value.
// Right subtree are items greater than the node value.

// The items are in order from left most leaf to the right most leaf
// however the left and right subtrees may be unbalanced meaning not the same
// depth depending on the order of inserts.  In other words if there are
// a large number of consecutive inserts with decreasing values the
// result will be a tree whose root is the first value inserted with a
// long left tree of decreasing values and no right hand tree at all.

struct TreeNode {
    TreeNode *pLeft;    // node that is less than the current node
    TreeNode *pRight;   // node that is greater than the current node
    int    iValue;      // value for this node
    int    iDepth;      // depth of this node in the tree, number of levels
};

typedef TreeNode *TreeHead;

const TreeHead emptyTree = 0;


// Since we use new to allocate tree nodes, the InsertNode () function could
// conceivably throw a memory allocation exception.
void InsertNode (int iValue, TreeHead &pTree)
{
    TreeNode TreeHeadInit = {emptyTree, emptyTree, iValue, 0};

    if (pTree == emptyTree) {
        // initialize the tree with this first item and return
        pTree = new TreeNode;
        *pTree = TreeHeadInit;
        return;
    }

    // Tree is not empty so lets find the place to put this new item to
    // be inserted.  We traverse the tree until we find the correct empty
    // spot in the tree and then we put it there.  If we come across the
    // value already in the tree then we do nothing and just return.
    TreeHead pTreeStruct = pTree;
    while (pTreeStruct != emptyTree) {
        // remember the depth of the current node as it will become the parent
        // node if we reach the outer most leaf and need to add a new node.
        TreeHeadInit.iDepth = pTreeStruct->iDepth;
        if (pTreeStruct->iValue == iValue) {
            // since we have found a node with the value specified then we
            // are done and we do nothing.
            return;  // do nothing
        } else  if (pTreeStruct->iValue < iValue) {
            if (pTreeStruct->pRight == emptyTree) {
                // we have reached the place where we need to add a new node to
                // extend the right tree with this greater value than the current
                // node contains.  allocate the node then break to initialize it.
                pTreeStruct = pTreeStruct->pRight = new TreeNode;
                break;
            }
            // the value to insert is greater than this node so we
            // traverse to the right where values greater than the
            // value of the current node are located.
            pTreeStruct = pTreeStruct->pRight;
        } else {
            if (pTreeStruct->pLeft == emptyTree) {
                // we have reached the place where we need to add a new node to
                // extend the left tree with this greater value than the current
                // node contains.  allocate the node then break to initialize it.
                pTreeStruct = pTreeStruct->pLeft = new TreeNode;
                break;
            }
            // the value to insert is less than this node so we
            // traverse to the left where values less than the
            // value of the current node are located.
            pTreeStruct = pTreeStruct->pLeft;
        }
    }

    // update this new node that has been added to the tree and
    // set its depth to be one more than the depth of its parent node.
    TreeHeadInit.iDepth++;
    *pTreeStruct = TreeHeadInit;
    return;
}

// print the tree starting with the lowest value to the highest value.
// for each node we want to print out the left item which is lower than
// the node's value and then the right item which is higher than the
// node's value.
void PrintTreeInOrder (TreeHead pTree)
{
    if (pTree != emptyTree) {
        PrintTreeInOrder (pTree->pLeft);
        std::cout << "  value " << pTree->iValue << " depth " << pTree->iDepth << std::endl;
        PrintTreeInOrder (pTree->pRight);
    }
}

// print the tree from the root element indenting the printed lines to give an
// idea as to a diagram of the tree and how the nodes are sequenced.
void PrintTreeInDepth (TreeHead pTree)
{
    if (pTree != emptyTree) {
        for (int i = 0; i < pTree->iDepth; i++) std::cout << "|..";
        std::cout << " value " << pTree->iValue << " depth " << pTree->iDepth;
        if (pTree->pLeft != emptyTree) {
            std::cout << " left " << pTree->pLeft->iValue << " ";
        } else {
            std::cout << " left NULL ";
        }
        if (pTree->pRight != emptyTree) {
            std::cout << " right " << pTree->pRight->iValue << " ";
        } else {
            std::cout << " right NULL ";
        }
        std::cout << std::endl;
        PrintTreeInDepth (pTree->pLeft);
        PrintTreeInDepth (pTree->pRight);
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    TreeHead myTree = emptyTree;

    // this is the first insert so will be the root of the unbalanced tree
    InsertNode (9, myTree);

    // now insert several items in decending order
    InsertNode (8, myTree);
    InsertNode (6, myTree);
    InsertNode (5, myTree);
    InsertNode (3, myTree);
    InsertNode (2, myTree);

    // now insert some other nodes haphazardly
    InsertNode (12, myTree);
    InsertNode (4, myTree);
    InsertNode (1, myTree);
    InsertNode (22, myTree);
    InsertNode (16, myTree);
    InsertNode (18, myTree);
    InsertNode (17, myTree);
    InsertNode (7, myTree);
    InsertNode (13, myTree);
    InsertNode (14, myTree);
    InsertNode (15, myTree);

    std::cout << "In order print" << std::endl;
    PrintTreeInOrder (myTree);
    std::cout << std::endl << std::endl;
    std::cout << "Depth diagram from Root using left traversal" << std::endl;
    PrintTreeInDepth (myTree);
    return 0;
}
In order print
  value 1 depth 6
  value 2 depth 5
  value 3 depth 4
  value 4 depth 5
  value 5 depth 3
  value 6 depth 2
  value 7 depth 3
  value 8 depth 1
  value 9 depth 0
  value 12 depth 1
  value 13 depth 4
  value 14 depth 5
  value 15 depth 6
  value 16 depth 3
  value 17 depth 5
  value 18 depth 4
  value 22 depth 2


Depth diagram from Root using left traversal
 value 9 depth 0 left 8  right 12
|.. value 8 depth 1 left 6  right NULL
|..|.. value 6 depth 2 left 5  right 7
|..|..|.. value 5 depth 3 left 3  right NULL
|..|..|..|.. value 3 depth 4 left 2  right 4
|..|..|..|..|.. value 2 depth 5 left 1  right NULL
|..|..|..|..|..|.. value 1 depth 6 left NULL  right NULL
|..|..|..|..|.. value 4 depth 5 left NULL  right NULL
|..|..|.. value 7 depth 3 left NULL  right NULL
|.. value 12 depth 1 left NULL  right 22
|..|.. value 22 depth 2 left 16  right NULL
|..|..|.. value 16 depth 3 left 13  right 18
|..|..|..|.. value 13 depth 4 left NULL  right 14
|..|..|..|..|.. value 14 depth 5 left NULL  right 15
|..|..|..|..|..|.. value 15 depth 6 left NULL  right NULL
|..|..|..|.. value 18 depth 4 left 17  right NULL
|..|..|..|..|.. value 17 depth 5 left NULL  right NULL

Java indentation in Level-order Tree print, not binary tree


By : 001010
Date : March 29 2020, 07:55 AM
should help you out You need to increment the indent when you start processing children, and then decrement it when you reach the end of a group of children.
You would be better off doing this whole thing using something like a recursive call rather than the queue though. The queue is adding a lot of complexity and not helping.
code :
recurseTree(Thing obj, String indent) {
    print(indent+obj.value);
    if (obj.children != null) {
       for (Thing child: obj.children) {
          recurseTree(child, indent+"   ");
       }
    }
}
recurseTree(root, "");

Could you help me to print a family tree made with binary search tree?


By : Exialin
Date : March 29 2020, 07:55 AM
To fix this issue So a couple of points. First of all a small style issue: You'd be better served using more descriptive variable names. You have a method signature that looks like:
code :
static void insertAncestor (String n, String s)
else if (n.compareTo(n)<0 && s.compareTo(s)<0){

For my C code to construct a binary search tree and print the tree on its side is not printing anything?


By : user2725647
Date : March 29 2020, 07:55 AM
Hope this helps I am trying to write a program to construct a binary search tree and print the tree on its side. Read the input from the user as a sequence of integers and output the tree indented based on depth and with one value on each line. However, my code is working but not printing anything on console? I think something might be wrong with my insert function but I am not sure. , The signature of insert is
code :
node *insert(node *t, int a) // t is a pointer to node
insert(&root, a);
root = insert(root, a);
Related Posts Related Posts :
  • Can std::threads be created / destroyed from global variables in a Windows DLL?
  • How to seperate a line in a txt file to components C++
  • c++ the difference between string using the assign function and directly using '=' to change the value
  • QT add Map QML Items via C++
  • long long int don't take long int well
  • Can the fragile base class problem occur in C++?
  • How do I write an array of contents into a text file?
  • How to stop execution of an async function when input is recieved in C++
  • Why is this code erroring when using a lambda?
  • Does std::(customization point) invoke the most appropriate overload?
  • Sharing a class between threads
  • Stack Program in C++
  • What is wrong with auto?
  • C++ A* algorithm not always having the target node in path
  • Crop an HBITMAP with C++ on Windows
  • understanding references in c++
  • Compiling standard library types
  • Sending argument to an .exe via SHELLEXECUTEINFO
  • Why I can't use i/10 in FOR LOOP, C++?
  • How to use PERF_SAMPLE_READ with mmap
  • Is there any way to iterate through a struct?
  • My character counting code is miscounting characters. Why?
  • Difference between std::resize(n) and std::shrink_to_fit in C++?
  • Wildcard for C++ concepts saying "accepting anything for this template argument"
  • Which of the objects of the class A would be created first in this code snippet?
  • Floating point math accuracy, c++ vs fortran
  • C++ initialize objects with packed array of integers
  • Picking a constructor to call
  • using function call in constructor gives different result c++
  • Using strcpy to copy elements of an char array to another array
  • Templated Constructor Specialization
  • Struggling to convert an integer into a linked list. Not sure what I'm doing wrong here
  • C++: Is it better to store a console output in a macro?
  • C++ - Exception in Constructor
  • AVX: matrix dot vector, but ignore diagonal
  • Pointer To Pointer passed by reference
  • Why is this operator< overload function invisible to STL algorithms?
  • What is the correct algorithm to perform double-float division?
  • In the case of using a std::unique_ptr to automatically deallocate memory upon exiting a scoped block, why not just use
  • C++: Iterating over a string vector and using the index for putenv
  • OpenCL Matrix Multiplication Using std::vector
  • template template parameter deduction: three different compilers three different behaviors
  • C++ pull a card from deck
  • File reading with and without new line
  • store strings in stable memory in c++
  • Why is static_cast used in QT's official document
  • iterator .end() from std::list returns "0xcdcdcdcdcdcdcdcd" but .begin() as expected
  • Is std::sqrt the same as sqrt in C++
  • Iterate through std::initializer_list
  • Codeblocks c++ code doesn't run in VS 19 (vector subscript out of range)
  • Why erase on std::vector promote iterator
  • how to destroy an object in C++
  • How to create Visual Studio 2015 solution from CMake
  • Using concepts for checking if a type T has a field F
  • constructor giving error: no matching function for call to
  • search top n% of a vector member C++
  • Is this reinterpret_cast problematic in principle, and/or in practice?
  • What is the following error doing? I do not see any error with the bounds
  • Two index's of an array have same memory adress
  • how do i avoid integer division in c++?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org