Postingan

Menampilkan postingan dengan label binary tree

Binary Tree PreOrder Traversal in Java - Recursion and Iteration Example

Gambar
Unlike a linked list and array which are linear data structure and can only be traversed linearly, there are several ways to traverse a binary tree because of its hierarchical nature. The tree traversal algorithms are mainly divided into two types, the depth-first algorithms , and breadth-first algorithms . As their name suggests, in a depth-first algorithm, the tree is traversed downwards (towards the depth) before the next sibling is visited, the PreOrder , InOrder and PostOrder traversal of a binary tree is actually depth-first traversal algorithms. On the breadth-first algorithm, also known as level order traversal, the entire breadth of the tree is traversed before moving to the next level, hence it is also known as level order traversal. There are other algorithms to traverse a binary tree as well e.g. Monte Carlo tree search, which concentrates on analyzing the most promising moves, but the pre-order, post-order, and in-order traversal are the most popular ways to traverse a bin...

How to Count Number of Leaf Nodes in a Binary Tree in Java - Iterative and Recursive Solution

Gambar
Hello guys, today I am going to talk about an interesting binary tree-based coding problem from Programming Job interviews. If you have attended a couple of technical interviews then there is a good chance that you already have seen this question about counting a number of leaf nodes in a binary tree. If you know how to solve this problem then it's well and good but if you haven't don't worry, you will learn in this article. If you follow this blog then you might know that I have discussed a lot of data structure and algorithms problems here, including array, linked list, hash table, binary tree, and binary search tree. If you remember then you can use the same algorithm to count a number of leaf nodes in the binary tree which we have used in the last article, while printing all leaf nodes of a binary tree in Java, using both recursion and iteration. The logic is the same for the leaf node, any node whose left and right children are null is known as a leaf node in a binary ...