A tree is Continuous tree if in each root to leaf path, absolute difference between keys of two adjacent is 1. We are given a binary tree, we need to check if tree is continuous or not.
Input : 3 / \ 2 4 / \ \ 1 3 5 Output: "Yes" // 3->2->1 every two adjacent node's absolute difference is 1 // 3->2->3 every two adjacent node's absolute difference is 1 // 3->4->5 every two adjacent node's absolute difference is 1 Input : 7 / \ 5 8 / \ \ 6 4 10 Output: "No" // 7->5->6 here absolute difference of 7 and 5 is not 1. // 7->5->4 here absolute difference of 7 and 5 is not 1. // 7->8->10 here absolute difference of 8 and 10 is not 1.
The solution requires a traversal of tree. The important things to check are to make sure that all corner cases are handled. The corner cases include, empty tree, single node tree, a node with only left child and a node with only right child.
In tree traversal, we recursively check if left and right subtree are continuous. We also check if difference between keys of current node’s key and its children keys is 1. Below is the implementation of the idea.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Tree Traversals (Inorder, Preorder and Postorder)
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Check for Children Sum Property in a Binary Tree
Improved By : andrew1234