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.
- XOR of path between any two nodes in a Binary Tree
- Maximum Path Sum in a Binary Tree
- Print path between any two nodes in a Binary Tree
- Minimum sum path between two leaves of a binary tree
- Print path between any two nodes in a Binary Tree | Set 2
- Longest Path with Same Values in 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
- Maximum Consecutive Increasing Path Length in Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print path from root to all nodes in a Complete Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Shortest path between two nodes in array like representation of binary tree
- Minimum and maximum node that lies in the path connecting two nodes in a 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 email@example.com. 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.