githubEdit

05(July) Vertical Width of a Binary Tree

05. Vertical Width of a Binary Tree

The problem can be found at the following link: Question Linkarrow-up-right

Problem Description

Given a Binary Tree, find and return the vertical width of the tree.

Examples:

Input:

         1
       /   \
      2     3
     / \   / \
    4   5 6   7
           \   \
            8   9

Output:

6

Explanation: The width of a binary tree is the number of vertical paths in that tree. The above tree contains 6 vertical lines.

Image

Approach

  1. Initialization:

    • Define a helper function solve that traverses the tree and updates the maximum and minimum horizontal distances from the root.

    • Use maxi and mini to track the maximum and minimum horizontal distances respectively.

    • Initialize maxi and mini to 0.

  2. Tree Traversal:

    • Perform a pre-order traversal (DFS) of the tree.

    • For each node, update maxi and mini based on the current horizontal distance x.

    • For the left child, the horizontal distance is x - 1.

    • For the right child, the horizontal distance is x + 1.

  3. Return:

    • The vertical width of the tree is maxi - mini + 1.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), as we traverse all the nodes of the tree once.

  • Expected Auxiliary Space Complexity: O(height of the tree), due to the recursion stack space used during the DFS traversal.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questionsarrow-up-right. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated