MODULE 6.4: TREE VIEWS & STRUCTURAL PROPERTIES — SIDE VIEWS, DIAMETER & LCA

A student-friendly guide to looking at a tree from different angles—Left, Right, Top, and Bottom views, plus questions like tree diameter, balance, and common ancestors.

💡 Summary: Looking at a Tree from Different Angles & Checking Its Shape

Once you know how to walk through a tree, a lot of fun problems ask what you see when looking at the tree from a certain angle—like standing on the left or right side of each row, or looking straight down from the top or up from the bottom into vertical columns.

Other classic questions check the overall shape and connections of a tree: how wide its longest path is (diameter), whether its left and right sides are roughly even in height (balanced), and who the closest shared boss or ancestor is for two nodes (Lowest Common Ancestor).

1. Left, Right, Top & Bottom Views of a Tree
To find top and bottom views, it helps to give each node a horizontal position (hd): the root starts at 0, going left subtracts 1 (hd - 1), and going right adds 1 (hd + 1):
  • Left & Right Views (Level by Level): As you go row by row from top to bottom, the first node on each row is what you see from the left, and the last node on each row is what you see from the right.
  • Top & Bottom Views (By Column / hd): Going top-to-bottom across levels, the first node you see in a column is the top view, and the last (lowest) node you see in that column is the bottom view.
View or Question How to Spot It Time Cost Extra Space
Left / Right View First / last node in each level Θ(N) Queue holding a level of nodes
Top View First node seen in each column (hd) from top down Θ(N) Map/dictionary for columns + queue
Bottom View Last (deepest) node seen in each column (hd) Θ(N) Map/dictionary for columns + queue
Diameter & LCA Check subtrees bottom-up in one pass Θ(N) Call stack up to tree height
Python (tree_views_left_right_top_bottom.py)
from collections import deque

class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def side_and_vertical_views(root):
    if not root:
        return [], [], [], []

    left_view, right_view = [], []
    top_map, bottom_map = {}, {}
    q = deque([(root, 0)])  # (node, horizontal_position)

    while q:
        level_len = len(q)
        for i in range(level_len):
            node, hd = q.popleft()

            if i == 0:
                left_view.append(node.val)
            if i == level_len - 1:
                right_view.append(node.val)

            if hd not in top_map:
                top_map[hd] = node.val     # First node in this column from top
            bottom_map[hd] = node.val      # Latest (lowest) node in this column

            if node.left:
                q.append((node.left, hd - 1))
            if node.right:
                q.append((node.right, hd + 1))

    sorted_hds = sorted(top_map.keys())
    top_view = [top_map[h] for h in sorted_hds]
    bottom_view = [bottom_map[h] for h in sorted_hds]
    return left_view, right_view, top_view, bottom_view

# Example tree:
#         1 (hd=0)
#        / \
#   2(-1)   3(+1)
#     \     /
#   4(0)  5(0)
tree = Node(1, Node(2, None, Node(4)), Node(3, Node(5), None))
lv, rv, tv, bv = side_and_vertical_views(tree)
print("Left View  :", lv)
print("Right View :", rv)
print("Top View   :", tv)
print("Bottom View:", bv)
Output: Left View : [1, 2, 4] Right View : [1, 3, 5] Top View : [2, 1, 3] Bottom View: [2, 5, 3]
2. Diameter, Balance Check & Lowest Common Ancestor (LCA)
Three classic tree questions you'll often see in exams and coding interviews:
  • Diameter (Longest Path Between Any Two Nodes): Imagine stretching a string between the two farthest nodes in the tree—the diameter is the length of that longest path. Notice it doesn't always have to pass through the root!
  • Height-Balanced Check: A tree is considered height-balanced if, at every node, the left and right subtree heights differ by at most 1.
  • Lowest Common Ancestor (LCA): The lowest (deepest) node that has both target nodes p and q under it (a node counts as a descendant of itself too).
C++ (diameter_balance_and_lca.cpp)
#include 
#include 
#include 
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};

// Returns height in edges (-1 for empty), and tracks longest path in `maxDiameter`
int calcHeightAndDiameter(TreeNode* root, int& maxDiameter) {
    if (!root) return -1;
    int lh = calcHeightAndDiameter(root->left, maxDiameter);
    int rh = calcHeightAndDiameter(root->right, maxDiameter);
    maxDiameter = max(maxDiameter, lh + rh + 2);
    return 1 + max(lh, rh);
}

// Returns height if balanced, or -1 if any part of the tree is out of balance
int checkBalancedHeight(TreeNode* root) {
    if (!root) return 0;
    int lh = checkBalancedHeight(root->left);
    if (lh == -1) return -1;
    int rh = checkBalancedHeight(root->right);
    if (rh == -1) return -1;
    if (abs(lh - rh) > 1) return -1;
    return 1 + max(lh, rh);
}

TreeNode* lowestCommonAncestor(TreeNode* root, int p, int q) {
    if (!root || root->val == p || root->val == q) return root;
    TreeNode* leftHit = lowestCommonAncestor(root->left, p, q);
    TreeNode* rightHit = lowestCommonAncestor(root->right, p, q);
    if (leftHit && rightHit) return root;
    return leftHit ? leftHit : rightHit;
}

int main() {
    TreeNode* root = new TreeNode(10);
    root->left = new TreeNode(20);
    root->right = new TreeNode(30);
    root->left->left = new TreeNode(40);
    root->left->right = new TreeNode(50);
    root->left->left->left = new TreeNode(60);

    int diameter = 0;
    int h = calcHeightAndDiameter(root, diameter);
    bool balanced = (checkBalancedHeight(root) != -1);
    TreeNode* lca = lowestCommonAncestor(root, 40, 50);

    cout << "Tree Height (edges) : " << h << "\n";
    cout << "Tree Diameter (edges): " << diameter << "\n";
    cout << "Is Height-Balanced?  : " << (balanced ? "Yes" : "No") << "\n";
    cout << "LCA of 40 and 50     : " << (lca ? lca->val : -1) << "\n";
    return 0;
}
Output: Tree Height (edges) : 3 Tree Diameter (edges): 4 Is Height-Balanced? : No LCA of 40 and 50 : 20
3. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Here are five real-world situations that feel like tree views, shared ancestors, or longest paths:
  • 1. Outermost Panels on Each Row (Left / Right View): When looking at nested panels or layers from the left or right edge, you see the outer item on each level.
  • 2. Top or Bottom Item in Each Column: Grouping items by vertical column lets you pick the topmost or bottommost one in each column.
  • 3. Finding Where Two Branches Meet (Lowest Common Ancestor): In version history or family/org charts, finding the nearest shared ancestor tells you where two paths split.
  • 4. Finding a Shared Manager Above Two Teams: When two people from different sub-teams need approval, walking up to their closest common manager makes sense.
  • 5. Longest Chain Between Two Endpoints (Diameter): Measures how far apart the two farthest connected points are in a tree-shaped network.
Python (realtime_tree_views_1_to_5.py)
# 3. Finding the lowest common manager/ancestor for two roles in a tree
class OrgNode:
    def __init__(self, role, left=None, right=None):
        self.role = role
        self.left = left
        self.right = right

def find_common_manager(root, role_a, role_b):
    if root is None or root.role in (role_a, role_b):
        return root
    left_res = find_common_manager(root.left, role_a, role_b)
    right_res = find_common_manager(root.right, role_a, role_b)
    if left_res and right_res:
        return root
    return left_res or right_res

org = OrgNode(
    "VP_Engineering",
    OrgNode("Backend_Lead", OrgNode("API_Dev"), OrgNode("DB_Engineer")),
    OrgNode("Frontend_Lead", OrgNode("UI_Dev"), OrgNode("QA_Lead"))
)

approver = find_common_manager(org, "DB_Engineer", "UI_Dev")
print("3. Common Escalation Approver:", approver.role)
Output: 3. Common Escalation Approver: VP_Engineering
4. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-world examples of checking tree balance, depth, and views:
  • 6. Checking If a Search Tree Stays Balanced: Keeping left and right heights close helps keep searches quick.
  • 7. Spotting Overly Deep or Lopsided Nesting: Helps catch trees that grew way deeper on one side than the other.
  • 8. Measuring Longest Call or Dependency Chains: Shows the longest chain of steps in a hierarchical setup.
  • 9. Bottom-Row Summary per Column: Picking the last item in each column shows the deepest entry in every vertical slot.
  • 10. First Item at Each Level in a Menu: Looking from the left picks the first item shown at each depth.
Python (realtime_tree_views_6_to_10.py)
# 6. Checking max depth and height-balance across a simple service tree
class ServiceNode:
    def __init__(self, name, left=None, right=None):
        self.name = name
        self.left = left
        self.right = right

def inspect_tree_balance(node):
    if node is None:
        return 0, True
    lh, l_bal = inspect_tree_balance(node.left)
    rh, r_bal = inspect_tree_balance(node.right)
    is_bal = l_bal and r_bal and abs(lh - rh) <= 1
    return 1 + max(lh, rh), is_bal

service_tree = ServiceNode(
    "Gateway",
    ServiceNode("AuthService", ServiceNode("TokenStore"), None),
    ServiceNode("BillingService")
)

max_depth, balanced = inspect_tree_balance(service_tree)
print(f"6. Max Call Depth: {max_depth} | Balanced?: {balanced}")
Output: 6. Max Call Depth: 3 | Balanced?: True
5. Exam & Study Tips for Students
Keep these three reminders in mind when solving view, diameter, or LCA problems:
  • The longest path (diameter) doesn't have to go through the root: A big branch deep on the left or right can have a longer path between two of its own nodes than any path going through the top root.
  • Go level by level for Top and Bottom views: Scanning row by row from the top makes sure earlier rows come before deeper rows in each column.
  • Compute height once per node instead of over and over: Calling a height function inside another recursion repeatedly can make your code slow—return the height up from each child call instead.
Python (tree_views_properties_checklist.py)
checkpoints = [
    "Side & Column Views: Left/Right = first/last per row; Top/Bottom = first/last per column.",
    "Diameter Tip: Don't assume the longest path passes through the root.",
    "LCA Idea: Find where the paths to both target nodes split or meet lowest down."
]

for item in checkpoints:
    print("*", item)
Output: * Side & Column Views: Left/Right = first/last per row; Top/Bottom = first/last per column. * Diameter Tip: Don't assume the longest path passes through the root. * LCA Idea: Find where the paths to both target nodes split or meet lowest down.