Cycling South Downs Way Guide

Discover the exhilarating adventure of cycling through the picturesque South Downs Way. This comprehensive guide provides all the information you need to embark on this thrilling journey. From…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Leetcode 314. Binary Tree Vertical Order Traversal Python solution

📑 Problem description:

Given a binary tree, return the vertical order traversal of its nodes’ values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Examples 1:

Examples 2:

Examples 3:

📝 Discussion

It is clear that the tree should be cut and put in the list like this:

The red number is the index in the list that we should return. Now the problem comes: We don’t know how many nodes will extend to the left if we just know the root node at the beginning, so the index of root node in the final returned list is also unknown.

It doesn’t matter! You can put the key and a dummy ‘index’ in a dictionary, and see what is the minimal index in the dictionary, and then move the indexes of the dictionary to the right. For example, if the index of the left-most node in the tree it -5, then every index in the dictionary should add 5 if we put them into the list.

Remember when you travel through the whole tree to achieve node values, you need to use level-order traversal instead of preorder, inorder, or postorder traversal.

Code:

Time complexity: O(n)

n is the number of nodes in the input tree.

To be precise, it should be O(n) + 2O(m)

m is the number of level in the input tree

Result:

Add a comment

Related posts:

Create in Times of Uncertainty

This article is a response to a tag by Helen Boss and Aurora Eliam, CMP and many others to answer questions about the lockdown. I am honored to answer them. Thank you guys, I appreciate this gesture…

Tips for playing online high limit coin pusher games

Coin pusher machine to play on Coin Woned Slots — Coin Pusher APP.Coin Woned is a mobile app from a real coin pushing game,and we provide a number of engaging coin pusher slots and arcade games from…