Binary Tree Data Structure
Binary Tree Data Structure
A tree whose elements have at most 2 children is called a binary tree. Since each
element in a binary tree can have only 2 children, we typically name them the left and
right child.
Binary Trees
by Nick Parlante
This article introduces the basic concepts of binary trees, and then works through a
series of practice problems with solution code in C/C++ and Java. Binary trees have
an elegant recursive pointer structure, so they are a good way to learn recursive
pointer algorithms.
Contents
Section 1. Binary Tree Structure -- a quick introduction to binary trees and the code
that operates on them
Section 2. Binary Tree Problems -- practice problems in increasing order of difficulty
Section 3. C Solutions -- solution code to the problems for C and C++ programmers
Section 4. Java versions -- how binary trees work in Java, with solution code
Stanford CS Education Library -- #110
This is article #110 in the Stanford CS Education Library. This and other free CS
materials are available at the library (http://cslibrary.stanford.edu/). That people
seeking education should have the opportunity to find it. This article may be used,
reproduced, excerpted, or sold so long as this paragraph is clearly reproduced.
Copyright 2000-2001, Nick Parlante, [email protected].
Related CSLibrary Articles
A "binary search tree" (BST) or "ordered binary tree" is a type of binary tree where
the nodes are arranged in order: for each node, all elements in its left subtree are less-
or-equal to the node (<=), and all the elements in its right subtree are greater than the
node (>). The tree shown above is a binary search tree -- the "root" node is a 5, and its
left subtree nodes (1, 3, 4) are <= 5, and its right subtree nodes (6, 9) are > 5.
Recursively, each of the subtrees must also obey the binary search tree constraint: in
the (1, 3, 4) subtree, the 3 is the root, the 1 <= 3 and 4 > 3. Watch out for the exact
wording in the problems -- a "binary search tree" is different from a "binary tree".
The nodes at the bottom edge of the tree have empty subtrees and are called "leaf"
nodes (1, 4, 6) while the others are "internal" nodes (3, 5, 9).
The node/pointer structure that makes up the tree and the code that
manipulates it
The algorithm, typically recursive, that iterates over the tree
When thinking about a binary tree problem, it's often a good idea to draw a few little
trees to think about the various cases.
Typical Binary Tree Code in C/C++
As an introduction, we'll look at the code for the two most basic binary search tree
operations -- lookup() and insert(). The code here works for C or C++. Java
programers can read the discussion here, and then look at the Java versions
in Section 4.
In C or C++, the binary tree is built with a node type like this...
struct node {
int data;
struct node* left;
struct node* right;
}
Lookup()
Given a binary search tree and a "target" value, search the tree to see if it contains
the target. The basic pattern of the lookup() code occurs in many recursive tree
algorithms: deal with the base case where the tree is empty, deal with the current
node, and then use recursion to deal with the subtrees. If the tree is a binary search
tree, there is often some sort of less-than test on the node to decide if the recursion
should go left or right.
/*
Given a binary tree, return true if a node
with the target data is found in the tree. Recurs
down the tree, chooses the left or right
branch by comparing the target to each node.
*/
static int lookup(struct node* node, int target) {
// 1. Base case == empty tree
// in that case, the target is not found so return false
if (node == NULL) {
return(false);
}
else {
// 2. see if found here
if (target == node->data) return(true);
else {
// 3. otherwise recur down the correct subtree
if (target < node->data) return(lookup(node->left, target));
else return(lookup(node->right, target));
}
}
}
The lookup() algorithm could be written as a while-loop that iterates down the tree.
Our version uses recursion to help prepare you for the problems below that require
recursion.
We take the value returned by change(), and use it as the new value for root. This
construct is a little awkward, but it avoids using reference parameters which confuse
some C and C++ programmers, and Java does not have reference parameters at all.
This allows us to focus on the recursion instead of the pointer mechanics. (For lots of
problems that use reference parameters, see CSLibrary #105, Linked List
Problems, http://cslibrary.stanford.edu/105/).
Insert()
Insert() -- given a binary search tree and a number, insert a new node with the given
number into the tree in the correct place. The insert() code is similar to lookup(), but
with the complication that it modifies the tree structure. As described above, insert()
returns the new tree pointer to use to its caller. Calling insert() with the number 5 on
this tree...
2
/ \
1 10
The solution shown here introduces a newNode() helper function that builds a single
node. The base-case/recursion structure is similar to the structure in lookup() -- each
call checks for the NULL case, looks at the node at hand, and then recurs down the
left or right subtree if needed.
/*
Helper function that allocates a new node
with the given data and NULL left and right
pointers.
*/
struct node* NewNode(int data) {
struct node* node = new(struct node); // "new" is like "malloc"
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/*
Give a binary search tree and a number, inserts a new node
with the given number in the correct place in the tree.
Returns the new root pointer which the caller should
then use (the standard trick to avoid using reference
parameters).
*/
struct node* insert(struct node* node, int data) {
// 1. If the tree is empty, return a new, single node
if (node == NULL) {
return(newNode(data));
}
else {
// 2. Otherwise, recur down the tree
if (data <= node->data) node->left = insert(node->left, data);
else node->right = insert(node->right, data);
The shape of a binary tree depends very much on the order that the nodes are inserted.
In particular, if the nodes are inserted in increasing order (1, 2, 3, 4), the tree nodes
just grow to the right leading to a linked list shape where all the left pointers are
NULL. A similar thing happens if the nodes are inserted in decreasing order (4, 3, 2,
1). The linked list shape defeats the lg(N) performance. We will not address that issue
here, instead focusing on pointers and recursion.
Reading about a data structure is a fine introduction, but at some point the only way to
learn is to actually try to solve some problems starting with a blank sheet of paper. To
get the most out of these problems, you should at least attempt to solve them before
looking at the solution. Even if your solution is not quite right, you will be building up
the right skills. With any pointer-based code, it's a good idea to make memory
drawings of a a few simple cases to see how the algorithm should work.
1. build123()
This is a very basic problem with a little pointer manipulation. (You can skip this
problem if you are already comfortable with pointers.) Write code that builds the
following little 1-2-3 binary search tree...
2
/ \
1 3
2. size()
This problem demonstrates simple binary tree traversal. Given a binary tree, count
the number of nodes in the tree.
3. maxDepth()
Given a binary tree, compute its "maxDepth" -- the number of nodes along the
longest path from the root node down to the farthest leaf node. The maxDepth of
the empty tree is 0, the maxDepth of the tree on the first page is 3.
4. minValue()
Given a non-empty binary search tree (an ordered binary tree), return the minimum
data value found in that tree. Note that it is not necessary to search the entire tree.
A maxValue() function is structurally very similar to this function. This can be solved
with recursion or with a simple while loop.
5. printTree()
Given a binary search tree (aka an "ordered binary tree"), iterate over the nodes to
print them out in increasing order. So the tree...
4
/ \
2 5
/ \
1 3
Produces the output "1 2 3 4 5". This is known as an "inorder" traversal of the tree.
Hint: For each node, the strategy is: recur left, print the node data, recur right.
6. printPostorder()
Given a binary tree, print out the nodes of the tree according to a bottom-up
"postorder" traversal -- both subtrees of a node are printed out completely before
the node itself is printed, and each left subtree is printed before the right subtree. So
the tree...
4
/ \
2 5
/ \
1 3
Produces the output "1 3 2 5 4". The description is complex, but the code is simple.
This is the sort of bottom-up traversal that would be used, for example, to evaluate an
expression tree where a node is an operation like '+' and its subtrees are, recursively,
the two subexpressions for the '+'.
7. hasPathSum()
We'll define a "root-to-leaf path" to be a sequence of nodes in a tree starting with
the root node and proceeding downward to a leaf (a node with no children). We'll
say that an empty tree contains no root-to-leaf paths. So for example, the following
tree has exactly four root-to-leaf paths:
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
Root-to-leaf paths:
path 1: 5 4 11 7
path 2: 5 4 11 2
path 3: 5 8 13
path 4: 5 8 4 1
For this problem, we will be concerned with the sum of the values of such a path -- for
example, the sum of the values on the 5-4-11-7 path is 5 + 4 + 11 + 7 = 27.
Given a binary tree and a sum, return true if the tree has a root-to-leaf path such that
adding up all the values along the path equals the given sum. Return false if no such
path can be found. (Thanks to Owen Astrachan for suggesting this problem.)
8. printPaths()
Given a binary tree, print out all of its root-to-leaf paths as defined above. This
problem is a little harder than it looks, since the "path so far" needs to be
communicated between the recursive calls. Hint: In C, C++, and Java, probably the
best solution is to create a recursive helper function printPathsRecur(node, int
path[], int pathLen), where the path array communicates the sequence of nodes that
led up to the current call. Alternately, the problem may be solved bottom-up, with
each node returning its list of paths. This strategy works quite nicely in Lisp, since it
can exploit the built in list and mapping primitives. (Thanks to Matthias Felleisen for
suggesting this problem.)
Given a binary tree, print out all of its root-to-leaf paths, one per line.
9. mirror()
Change a tree so that the roles of the left and right pointers are swapped at every
node.
The solution is short, but very recursive. As it happens, this can be accomplished
without changing the root node pointer, so the return-the-new-root construct is not
necessary. Alternately, if you do not want to change the tree nodes, you may construct
and return a new mirror tree based on the original tree.
10. doubleTree()
For each node in a binary search tree, create a new duplicate node, and insert the
duplicate as the left child of the original node. The resulting tree should still be a
binary search tree.
As with the previous problem, this can be accomplished without changing the root
node pointer.
11. sameTree()
Given two binary trees, return true if they are structurally identical -- they are made
of nodes with the same values arranged in the same way. (Thanks to Julie Zelenski
for suggesting this problem.)
Suppose you are building an N node binary search tree with the values 1..N. How
many structurally different binary search trees are there that store those values? Write
a recursive function that, given the number of distinct values, computes the number of
structurally unique binary search trees that store those values. For example,
countTrees(4) should return 14, since there are 14 structurally unique binary search
trees that store 1, 2, 3, and 4. The base case is easy, and the recursion is short but
dense. Your code should not construct any actual trees; it's just a counting problem.
d. 5 -> FALSE, the 6 is ok with the 2, but the 6 is not ok with the 5
/ \
2 7
/ \
1 6
For the first two cases, the right answer can be seen just by comparing each node to
the two nodes immediately below it. However, the fourth case shows how checking
the BST quality may depend on nodes which are several layers apart -- the 5 and the 6
in that case.
13 isBST() -- version 1
Suppose you have helper functions minValue() and maxValue() that return the min
or max int value from a non-empty tree (see problem 3 above). Write an isBST()
function that returns true if a tree is a binary search tree and false otherwise. Use
the helper functions, and don't forget to check every node in the tree. It's ok if your
solution is not very efficient. (Thanks to Owen Astrachan for the idea of having this
problem, and comparing it to problem 14)
/*
Returns true if the given tree is a binary search tree
(efficient version).
*/
int isBST2(struct node* node) {
return(isBSTRecur(node, INT_MIN, INT_MAX));
}
/*
Returns true if the given tree is a BST and its
values are >= min and <= max.
*/
int isBSTRecur(struct node* node, int min, int max) {
15. Tree-List
The Tree-List problem is one of the greatest recursive pointer problems ever devised,
and it happens to use binary trees as well. CLibarary
#109 http://cslibrary.stanford.edu/109/ works through the Tree-List problem in
detail and includes solution code in C and Java. The problem requires an
understanding of binary trees, linked lists, recursion, and pointers. It's a great
problem, but it's complex.
root->left = lChild;
root->right= rChild;
return(root);
}
// call newNode() three times, and use only one local variable
struct node* build123b() {
struct node* root = newNode(2);
root->left = newNode(1);
root->right = newNode(3);
return(root);
}
/*
Build 123 by calling insert() three times.
Note that the '2' must be inserted first.
*/
struct node* build123c() {
struct node* root = NULL;
root = insert(root, 2);
root = insert(root, 1);
root = insert(root, 3);
return(root);
}
return(current->data);
}
printTree(node->left);
printf("%d ", node->data);
printTree(node->right);
}
Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*/
int hasPathSum(struct node* node, int sum) {
// return true if we run out of tree and sum==0
if (node == NULL) {
return(sum == 0);
}
else {
// otherwise check both subtrees
int subSum = sum - node->data;
return(hasPathSum(node->left, subSum) ||
hasPathSum(node->right, subSum));
}
}
/*
Recursive helper function -- given a node, and an array containing
the path from the root node up to but not including this node,
print out all the root-leaf paths.
*/
void printPathsRecur(struct node* node, int path[], int pathLen) {
if (node==NULL) return;
*/
void doubleTree(struct node* node) {
struct node* oldLeft;
if (node==NULL) return;
// do the subtrees
doubleTree(node->left);
doubleTree(node->right);
if (numKeys <=1) {
return(1);
}
else {
// there will be one value at the root, with whatever remains
// on the left and right each forming their own subtrees.
// Iterate through all the values that could be the root...
int sum = 0;
int left, right, root;
return(sum);
}
}
/*
Returns true if the given tree is a BST and its
values are >= min and <= max.
*/
int isBSTUtil(struct node* node, int min, int max) {
if (node==NULL) return(true);
// BinaryTree.java
public class BinaryTree {
// Root node pointer. Will be null for an empty tree.
private Node root;
/*
--Node--
The binary tree is built using this nested node class.
Each node stores one data element, and has left and right
sub-tree pointer which may be null.
The node is a "dumb" nested class -- we just use it for
storage; it does not have any methods.
*/
private static class Node {
Node left;
Node right;
int data;
/**
Creates an empty binary tree -- a null root pointer.
*/
public void BinaryTree() {
root = null;
}
/**
Returns true if the given target is in the binary tree.
Uses a recursive helper.
*/
public boolean lookup(int data) {
return(lookup(root, data));
}
/**
Recursive lookup -- given a node, recur
down searching for the given data.
*/
private boolean lookup(Node node, int data) {
if (node==null) {
return(false);
}
if (data==node.data) {
return(true);
}
else if (data<node.data) {
return(lookup(node.left, data));
}
else {
return(lookup(node.right, data));
}
}
/**
Inserts the given data into the binary tree.
Uses a recursive helper.
*/
public void insert(int data) {
root = insert(root, data);
}
/**
Recursive insert -- given a node pointer, recur down and
insert the given data into the tree. Returns the new
node pointer (the standard way to communicate
a changed pointer back to the caller).
*/
private Node insert(Node node, int data) {
if (node==null) {
node = new Node(data);
}
else {
if (data <= node.data) {
node.left = insert(node.left, data);
}
else {
node.right = insert(node.right, data);
}
}
return(node); // in any case, return the new pointer to the caller
}
root.left = lChild;
root.right= rChild;
}
/**
Build 123 using only one pointer variable.
*/
public void build123b() {
root = new Node(2);
root.left = new Node(1);
root.right = new Node(3);
}
/**
Build 123 by calling insert() three times.
Note that the '2' must be inserted first.
*/
public void build123c() {
root = null;
root = insert(root, 2);
root = insert(root, 1);
root = insert(root, 3);
}
/**
Finds the min value in a non-empty binary search tree.
*/
private int minValue(Node node) {
Node current = node;
while (current.left != null) {
current = current.left;
}
return(current.data);
}
Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*/
public boolean hasPathSum(int sum) {
return( hasPathSum(root, sum) );
}
/**
Recursive printPaths helper -- given a node, and an array containing
the path from the root node up to but not including this node,
prints out all the root-leaf paths.
*/
private void printPaths(Node node, int[] path, int pathLen) {
if (node==null) return;
/**
Utility that prints ints from an array on one line.
*/
private void printArray(int[] ints, int len) {
int i;
for (i=0; i<len; i++) {
System.out.print(ints[i] + " ");
}
System.out.println();
}
9. mirror() Solution (Java)
/**
Changes the tree into its mirror image.
// do the subtrees
doubleTree(node.left);
doubleTree(node.right);
/**
Recursive helper -- recurs down two trees in parallel,
checking to see if they are identical.
*/
boolean sameTree(Node a, Node b) {
// 1. both empty -> true
if (a==null && b==null) return(true);
return(sum);
}
}
/**
Recursive helper -- checks if a tree is a BST
using minValue() and maxValue() (not efficient).
*/
private boolean isBST(Node node) {
if (node==null) return(true);
/**
Efficient BST helper -- Given a node, and min and max values,
recurs down the tree to verify that it is a BST, and that all
its nodes are within the min..max range. Works in O(n) time --
visits each node only once.
*/
private boolean isBST2(Node node, int min, int max) {
if (node==null) {
return(true);
}
else {
// left should be in range min...node.data
boolean leftOk = isBST2(node.left, min, node.data);
return(rightOk);
}
}
A binary tree is a hierarchical data structure in which each node has at most two
children generally referred as left child and right child.
Each node contains three components:
3. Data element
The topmost node in the tree is called the root. An empty tree is represented
by NULL pointer.
A representation of binary tree is shown:
Child: A node directly connected to another node when moving away from the root.
Height of a node: Number of edges from the node to the deepest leaf. Height of the
In the above binary tree we see that root node is A. The tree has 10 nodes with 5
internal nodes, i.e, A,B,C,E,G and 5 external nodes, i.e, D,F,H,I,J. The height of the
tree is 3. B is the parent of D and E while D and E are children of B.
Advantages of Trees
Trees are so useful and frequently used, because they have some very serious
advantages:
Rooted binary tree: It has a root node and every node has atmost two children.
Full binary tree: It is a tree in which every node in the tree has either 0 or 2 children.
1, i.e, l = L+1.
Perfect binary tree: It is a binary tree in which all interior nodes have two children and
Complete binary tree: It is a binary tree in which every level, except possibly the last, is
Balanced binary tree: A binary tree is height balanced if it satisfies the following
constraints:
o The left and right subtrees' heights differ by at most one, AND
Given A binary Tree, how do you count all the full nodes (Nodes which have both
children as not NULL) without using recursion and with recursion? Note leaves should
not be touched as they have both children as NULL.
Nodes 2 and 6 are full nodes has both child’s. So count of full nodes in the above tree is
2
Recommended: Please try your approach on {IDE} first, before moving
on to the solution.
Method: Iterative
The idea is to use level-order traversal to solve this problem efficiently.
1) Create an empty Queue Node and push root node to Queue.
2) Do following while nodeQeue is not empty.
a) Pop an item from Queue and process it.
a.1) If it is full node then increment count++.
b) Push left child of popped item to Queue, if available.
c) Push right child of popped item to Queue, if available.
Below is the implementation of this idea.
In C++
C++ play_arrow
Java brightness_4
// C++ program to count
Python
C# // full nodes in a Binary Tree
// a binary tree }
// If tree is empty given data and NULL left and right
pointers. */
if (!node)
struct Node* newNode(int data)
return 0;
{
queue<Node *> q;
struct Node* node = new Node;
node->data = data;
// Do level order traversal
starting from root node->left = node->right =
NULL;
int count = 0; // Initialize count
of full nodes return (node);
q.push(node); }
while (!q.empty())
/* 2
/ \ Output:
7 5 2
\ \
Time Complexity: O(n)
Auxiliary Space : O(n) where, n is
6 9 number of nodes in given binary tree
/ \ /
1 11 4
*/
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left =
newNode(1);
root->left->right->right =
newNode(11);
root->right->right = newNode(9);
root->right->right->left =
newNode(4);
return 0;
chevron_right
2
In Java Queue<Node> queue = new
LinkedList<Node>();
// Do level order traversal starting from root
C++ queue.add(root);
Java int count=0; // Initialize count of full nodes
Python while (!queue.isEmpty())
{
C#
filter_none Node temp = queue.poll();
if (temp.left!=null && temp.right!=null)
edit count++;
play_arrow // Enqueue left child
brightness_4 if (temp.left != null)
{
queue.add(temp.left);
// Java program to count }
// full nodes in a Binary Tree
// using Iterative approach
import java.util.Queue; // Enqueue right child
import java.util.LinkedList; if (temp.right != null)
{
queue.add(temp.right);
// Class to represent Tree node }
class Node }
{ return count;
int data; }
Node left, right;
public static void main(String args[])
public Node(int item) {
{ /* 2
data = item; / \
left = null; 7 5
right = null; \ \
} 6 9
} / \ /
1 11 4
// Class to count full nodes of Tree Let us create Binary Tree as shown
class BinaryTree */
{ BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node(2);
Node root;
/* Function to get the count of full
Nodes in
C++
a binary tree*/
int getfullCount() Java
{ Python
// If tree is empty
if (root==null) C#
return 0;
filter_none
// Initialize empty queue. edit
{
play_arrow queue.add(temp.left);
brightness_4 }
// Java program to count // Enqueue right child
// full nodes in a Binary Tree if (temp.right != null)
// using Iterative approach {
import java.util.Queue; queue.add(temp.right);
import java.util.LinkedList; }
}
return count;
// Class to represent Tree node
}
class Node
{
int data; public static void main(String args[])
Node left, right; {
/* 2
/ \
public Node(int item)
7 5
{
\ \
data = item;
6 9
left = null;
/ \ /
right = null;
1 11 4
}
Let us create Binary Tree as shown
}
*/
BinaryTree tree_level = new BinaryTree();
// Class to count full nodes of Tree tree_level.root = new Node(2);
class BinaryTree tree_level.root.left = new Node(7);
{ tree_level.root.right = new Node(5);
tree_level.root.left.right = new Node(6);
Node root; tree_level.root.left.right.left = new Node(1);
tree_level.root.left.right.right = new Node(11);
tree_level.root.right.right
/* Function to get the count of full Nodes in = new Node(9);
a binary tree*/ tree_level.root.right.right.left = new Node(4);
int getfullCount()
{ System.out.println(tree_level.getfullCount());
// If tree is empty
if (root==null) }
return 0; }
// Initialize empty queue. chevron_right
2
Queue<Node> queue = new LinkedList<Node>();
// Do level order traversal starting from root
queue.add(root); Output:
2
int count=0; // Initialize count of full nodes
while (!queue.isEmpty()) Time Complexity: O(n)
{ Auxiliary Space : O(n)
where, n is number of
Node temp = queue.poll(); nodes in given binary
if (temp.left!=null && temp.right!=null)
count++;
tree
tree_level.root.left
= new Node(7);
// Enqueue left child tree_level.root.righ
if (temp.left != null)
t = new Node(5);
tree_level.root.left
.right = new Node(6);
tree_level.root.left.r
ight.left = new
Node(1);
tree_level.root.left.r
ight.right=new
Node(11);
tree_level.root.right.
right = new Node(9);
tree_level.root.right.
right.left=new
Node(4);
System.out.println(tr
ee_level.getfullCount(
));
}
}
chevron_right
2
Output:
2
Time Complexity: O(n)
Auxiliary Space : O(n) where, n is
number of nodes in given binary tree
if (root == null)
return 0;
// Initialize empty queue.
Queue<Node> queue = new Queue<Node>();
// Do level order traversal starting from root
queue.Enqueue(root);
count = 0; // Initialize count of full nodes
while (queue.Count != 0)
{
Method: Recursive
The idea is to traverse the tree in postorder. If the current node is full, we
increment result by 1 and add returned values of left and right subtrees.
chevron_right
// Driver program 2
int main(void)
Output:2
{
Time Complexity: O(n)
/* 2 Auxiliary Space : O(n)
where, n is number of nodes in given
/ \ binary tree
7 5
\ \
6 9
/ \ /
1 11 4
*/
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
/* Helper function that allocates a new
Node with the given data and NULL left
and right pointers. */
static Node newNode(int data)
// Driver program
public static void main(String[] args)
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
// Driver program
public static void Main()
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
IN C#
Node root = newNode(2);
// C# program to count full nodes in a Binary Tree root.left = newNode(7);
using System; root.right = newNode(5);
root.left.right = newNode(6);
class GfG root.left.right.left = newNode(1);
{ root.left.right.right = newNode(11);
root.right.right = newNode(9);
// A binary tree Node has data, pointer to left root.right.right.left = newNode(4);
// child and a pointer to right child
public class Node Console.WriteLine(getfullCount(root));
{ }
public int data; }
public Node left, right;
} /* This code contributed by PrinciRaj1992 */
// Function to get the count of full Nodes in
// a binary tree
static int getfullCount(Node root) Output:2
{ Time Complexity: O(n)
if (root == null) Auxiliary Space : O(n)
return 0;
where, n is number of nodes in given
binary tree
int res = 0;
if (root.left != null && root.right != null)
res++;
res += (getfullCount(root.left) + getfullCount
(root.right));
Similar Articles:
Given a binary tree, how do you remove all the half nodes?