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;
}
}
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.
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.
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.
Use recursion.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With