Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scan tree structure from bottom up?

If given the following tree structure or one similar to it:

enter image description here

I would want the string ZYXWVUT returned. I know how to do this with a binary tree but not one that can have more than child nodes. Any help would be much appreciated.

like image 619
user2998228 Avatar asked Nov 19 '13 03:11

user2998228


People also ask

How do you traverse a tree bottom up?

First print string of left most subtree(from bottom to top) then print string of second left subtree(from bottom to top) then print for third left subtree and so on.

How do you find the bottom view of a tree?

The bottom view of a binary tree can be printed by hashing and level order traversal of the binary tree.

Which tree uses bottom up approach for creation?

When you create an R-tree index, by default, the access method builds the index using a fast bulk-loading algorithm, called bottom-up building.

How do you traverse a tree from root to leaf?

Traverse an n-ary tree, starting from a leaf node, up to the root, such that no node is traversed before all it's children are traversed. First node traversed will always be the leaf node, last node traversed will always be the root node.


2 Answers

This is called a post-order traversal of a tree: you print the content of all subtrees of a tree before printing the content of the node itself.

Post-order traversal

This can be done recursively, like this (pseudocode):

function post_order(Tree node)
    foreach n in node.children
        post_order(n)
    print(node.text)
like image 55
Sergey Kalinichenko Avatar answered Oct 05 '22 16:10

Sergey Kalinichenko


If you are maintaining an ArrayList (say node_list) to track the number of nodes branching of from the current tree node, you can traverse the tree from the root till you find a node that has an empty node_list. This way you will be able to identify the leaf nodes of the tree. A recursive approach would work for this case. I haven't tested the code but I believe this should work for what you have asked:

If you are maintaining something similar to the class below to build your tree:

class Node {
     String data;
     ArrayList<Node> node_list;}

The following recursive function might be what you are looking for:

public void traverse_tree(Node n){
    if(n.node_list.isEmpty()){
        System.out.print(n.data);
    }
    else{
        for(Node current_node:n.node_list){
            traverse_tree(current_node);
        }
        System.out.println(n.data);
    }
}

Essentially what you are looking at is the Post-order Depth First traversal of the tree.

like image 24
Rohit Jose Avatar answered Oct 05 '22 17:10

Rohit Jose