Question: Given a binary tree , Count leaf nodes A leaf node is a node which doesn't have any children. e.g. for the below tree 2
Given a binary tree, Count leaf nodes
A leaf node is a node which doesn't have any children.
e.g. for the below tree
2
/
4 5
/
1 3
Here 1, 3 and 5 are leaf nodes.
The binary tree should be created using structure'struct node'.
Write a function:
int solution(struct node * R)
that accept root node of binary tree R of type 'struct node'.The function should return the count of a leaf nodes.
Input
5
1 3 4 5 2
1 4 3 2 5
Where,
- First line of input represents the size of an arrayN.
- Second line contains post-order arrayrepresentation.
- Third line contains in-order array representation.
Output
3
Assume that,
- Structure “struct node” is already defined.
- N is an integer within the range [1 to 10000].
- Array elements are integers within the range [-2147483648to 2147483647].
use the code below:
import java.util.*;
public class Solution {
static class Node {
int key;
Node left;
Node right;
Node(int n) {
key = n;
left = null;
right = null;
}
}
static Node createTree(int in[], int post[], intn) {
if(n <= 0) {
return null;
}
if(n == 1) {
return new Node(in[0]);
}
int rootNode =post[n-1];
Node root = newNode(rootNode);
int i;
for(i = 0; i < n;i++) {
if(in[i] == rootNode) {
break;
}
}
int leftlen = i,rightlen = n-i-1;
int leftin[] = newint[leftlen];
int rightin[] = newint[rightlen];
System.arraycopy(in,0,leftin,0,leftlen);
System.arraycopy(in,leftlen+1,rightin,0,rightlen);
int leftpost[] = newint[leftlen];
int rightpost[] = newint[rightlen];
System.arraycopy(post,0,leftpost,0,leftlen);
System.arraycopy(post,leftlen,rightpost,0,rightlen);
root.left =createTree(leftin,leftpost,leftlen);
root.right =createTree(rightin,rightpost,rightlen);
return root;
}
static int solution(Node node) {
int numOfLeafNodes =0;
// TODO: Write your codehere
returnnumOfLeafNodes;
}
public static void main(String[] args) {
Scanner sc = newScanner(System.in);
int n =sc.nextInt();
if(n == 0) {
return;
}
int in[] = newint[n];
int post[] = newint[n];
for(int i = 0; i < n;i++) {
post[i] = sc.nextInt();
}
for(int i = 0; i < n;i++) {
in[i] = sc.nextInt();
}
Node root =createTree(in,post,n);
int ans =solution(root);
System.out.println(ans);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
