0 votes
41 views
in Data Structure And Algorithm by (3.7k points)
How to find leaf nodes in a tree java?

1 Answer

0 votes
by (3.7k points)
In a tree data structure, leaf node means which nodes have not any child is called leaf node in a tree.

          Node (leaf)
           /    \
left(null)  Right(null)

See the following example to print the all leaf nodes in binary tree:-

public void printLeafNode(Node root){
        if(root == null)
            return;
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while(!stack.empty()){
            Node temp = stack.pop();
            if(temp.left == null && temp.right == null)
                System.out.print(temp.data + " ");
            if(temp.right != null)
                stack.push(temp.right);
            if(temp.left != null)
                stack.push(temp.left);
        }
    }

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...