Given the root of a tree, the task is to find the count of nodes which are greater than all of its ancestors.
Input: 4 / \ 5 2 / \ 3 6 Output: 3 The nodes are 4, 5 and 6. Input: 10 / \ 8 6 \ \ 3 5 / 1 Output: 1
Approach: The problem can be solved using dfs. In every function call, pass a variable maxx which stores the maximum among all the nodes traversed so far and every node whose value is greater than maxx is the node that satisfies the given condition. Hence, increment the count.
Below is the implementation of the above approach:
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.
- Print common nodes on path from root (or common ancestors)
- Count of all prime weight nodes between given nodes in the given Tree
- Number of nodes greater than a given value in n-ary tree
- Delete nodes which have a greater value on right side using recursion
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Count pairs in BST with sum greater than K
- Print Ancestors of a given node in Binary Tree
- Iterative method to find ancestors of a given binary tree
- Count BST nodes that lie in a given range
- Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
- Count the nodes in the given tree whose weight is even
- Count the nodes whose sum with X is a Fibonacci number
- Count Non-Leaf nodes in a Binary Tree
- Count the nodes in the given tree whose weight is prime
- Count the nodes of the given tree whose weight has X as a factor
- Find count of pair of nodes at even distance
- Count of nodes which are at a distance X from root and leaves
- Count of nodes having odd divisors in the given subtree for Q queries
- Count the nodes whose weight is a perfect square
- Count of Nodes whose both immediate children are its prime factors
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.