The paths that form an AP in the given tree from root to leaf are:
- 1->3->5 (A.P. with common difference 2)
- 1->6->11 (A.P. with common difference 5)
The path that form an AP in the given tree from root to leaf is 1->10->19 (A.P. with difference 9)
Approach: The problem can be solved using the Preorder Traversal. Follow the steps below to solve the problem:
- Perform Preorder Traversal on the given binary tree.
- Initialize an array arr to store the path.
- Initialize count = 0, to store the count of paths which forms an A.P.
- After reaching the leaf node, check if the current elements in the array(i.e. the node values from root to leaf path) forms an A.P..
- If so, increment the count
- After the complete traversal of the tree, print the count.
Below is the implementation of above approach:
Time Complexity: O(N)
Auxiliary Space: O(h), where h is the height of binary tree.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Given a binary tree, print all root-to-leaf paths
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Root to leaf paths having equal lengths in a Binary Tree
- Maximize count of set bits in a root to leaf path in a binary tree
- Print all the paths from root, with a specified sum in Binary tree
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Find all root to leaf path sum of a Binary Tree
- Find maximum GCD value from root to leaf in a Binary tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Find the maximum sum leaf to root path in a Binary Tree
- Sum of all the numbers that are formed from root to leaf paths
- Print root to leaf paths without using recursion
- Remove nodes on root to leaf paths of length < K
- Print all root to leaf paths with there relative positions
- Count all k-sum paths in a Binary Tree
- Count even paths in Binary Tree
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.