Given a binary tree of 0s and 1s, the task is to find the maximum number of 1s in any path in the tree. The path may start and end at any node in the tree.
Input: 1 / \ 0 1 / \ 1 1 / \ 1 0 Output: 4
- A function countUntil has been created which returns the maximum count of 1 in any vertical path below that node.
- This path must be a single path and this path must include at-most one child of the node as well as its itself. i.e countUntil returns the max count of 1 in either left child or right child and also includes itself in count if its value is 1.
- So, from any node countUntil(node->left) + countUntil(node->right) + node->value will give the number of 1s in the path which contains the node and its left and right path and no ancestor of the node is considered.
- Taking the maximum of all nodes will give the required answer.
Below is the implementation of the above approach
Time Complexity: O(n)
where n is number of nodes in 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.
- Maximize count of set bits in a root to leaf path in a binary tree
- Maximum Path Sum in a Binary Tree
- Maximum XOR path of a Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Print all Coprime path of a Binary Tree
- Print path between any two nodes in a Binary Tree | Set 2
- Minimum sum path between two leaves of a binary tree
- Longest Path with Same Values in a Binary Tree
- Print path between any two nodes in a Binary Tree
- Find all root to leaf path sum of a Binary Tree
- Find the maximum path sum between two leaves of a binary tree
- Print path from root to a given node in a binary tree
- Sort the path from root to a given node in a Binary Tree
- Shortest path between two nodes in array like representation of binary tree
- Print path from root to all nodes in a Complete Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Print the first shortest root to leaf path in a Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Maximum Consecutive Increasing Path Length 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.