📌  相关文章
📜  国际空间研究组织 | ISRO CS 2016 |问题 12(1)

📅  最后修改于: 2023-12-03 14:50:47.438000             🧑  作者: Mango

ISRO CS 2016 Question 12

This is a question from the ISRO CS 2016 examination.

Problem Statement

Given a binary tree and a key node, find the vertical order traversal of the subtree rooted at the given key node.

Example

Input:

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

Key Node: 5

Output:

4
2
5
1
3
6
7
Approach

To solve this problem, we can use a HashMap to store the vertical order of each node in the tree. The vertical order of a node is the horizontal distance of that node from the root node. We can use a depth-first search (DFS) to traverse the tree and update the HashMap accordingly.

First, we find the horizontal distance of the key node from the root node. Then, we traverse the binary tree using DFS and update the vertical order of the node accordingly. We also maintain the minimum and maximum horizontal distance of the nodes. Finally, we iterate from the minimum to the maximum horizontal distance and print the nodes in the order they appear in the HashMap.

Code
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
        self.hd = None

def getVerticalOrder(root, hd, m):
    if root is None:
        return

    if hd in m:
        m[hd].append(root.val)
    else:
        m[hd] = [root.val]

    getVerticalOrder(root.left, hd - 1, m)
    getVerticalOrder(root.right, hd + 1, m)

def verticalOrderTraversal(root, key):
    # Find the horizontal distance of the key node from the root node
    key_hd = None

    def findKey(node, hd):
        nonlocal key_hd
        if node is None:
            return

        if node.val == key:
            key_hd = hd

        findKey(node.left, hd - 1)
        findKey(node.right, hd + 1)

    findKey(root, 0)

    # Traverse the tree and update the Hashmap
    m = {}
    getVerticalOrder(root, 0, m)

    # Print the nodes in the vertical order
    for hd in range(key_hd - 1, key_hd + 2):
        if hd in m:
            print("\n".join(map(str, m[hd])))

# Example usage
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, None, TreeNode(6, None, TreeNode(7))))
verticalOrderTraversal(root, 5)

The above code is written in Python and uses a recursive approach to find the vertical order traversal of the subtree rooted at the given key node. The output is printed to console instead of returning it as a string.