Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all leaf nodes of a tree?

Tags:

java

Suppose I have a node in a tree, how can I get all leaf nodes whose ancestor is this node?

I have defined the TreeNode like this:

public class TreeNode<T>
{
    /** all children of the node */
    private List<TreeNode<T>> children = new ArrayList<TreeNode<T>>();
    /** the parent of the node, if the node is root, parent = null */
    private TreeNode<T> parent = null;
    /** the stored data of the node */
    private T data = null;

    /** the method I want to implement */
    public Set<TreeNode<T>> getAllLeafNodes()
    {
        Set<TreeNode<T>> leafNodes = new HashSet<TreeNode<T>>();
        return leafNodes;
    }
}
like image 984
Frank Avatar asked Jul 13 '15 13:07

Frank


People also ask

How do you calculate leaf nodes in a tree?

Algorithm to count leaf nodes in a binary treeIf root is a leaf node, return 1. To determine a leaf node check if both left and right children's are NULL. Recursively, calculate the count of leaf nodes in left and right sub tree. Return the sum of leaf node count of left and right sub tree.

How do you sum all nodes in a tree?

If the tree is not empty, traverse through left subtree, calculate the sum of nodes and store it in sumLeft. Then, traverse through the right subtree, calculate the sum of nodes and store it in sumRight. Finally, calculate total sum = temp. data + sumLeft + sumRight.

How do you find the sum of all leaf nodes in a binary tree?

Given a binary tree, find the sum of all the leaf nodes. The idea is to traverse the tree in any fashion and check if the node is the leaf node or not. If the node is the leaf node, add node data to sum variable.


1 Answers

Use recursion.

  • if the node itself is a leaf, return it
  • otherwise, return all the leaf-nodes of its children

Something like this (not tested):

public Set<TreeNode<T>> getAllLeafNodes() {
    Set<TreeNode<T>> leafNodes = new HashSet<TreeNode<T>>();
    if (this.children.isEmpty()) {
        leafNodes.add(this);
    } else {
        for (TreeNode<T> child : this.children) {
            leafNodes.addAll(child.getAllLeafNodes());
        }
    }
    return leafNodes;
}
like image 132
tobias_k Avatar answered Sep 18 '22 16:09

tobias_k