We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Data Structures
- Trees
- Tree : Top View
- Discussions
Tree : Top View
Tree : Top View
Sort by
recency
|
949 Discussions
|
Please Login in order to post a comment
Title: Why is my top view function returning incorrect results for a binary search tree?
Hi everyone,
I’m trying to implement the top view of a binary search tree in Java, but my output isn’t matching my expectations. After debugging my code, I suspect I may not fully understand the concept of the top view, and I’m getting an incorrect result.
Problem:
I’ve inserted nodes into a binary search tree in the following order:
My Approach:
I’m using the following code to calculate the top view:
Issue:
When I run the program with the above input, I get the following output:
However, the expected output should be:
Thank you in advance for your help!
This version should make your issue and expectations clear to others, inviting them to help you debug the code further.
Hello everyone!
I've struggles with solving this problem.
1) I can't understand the input provided, I assume it's a node with data, left and right properties.
2) And this is my javascript solution which prints nothing:
A Picture is worth a thousand words
Image
For left subtree keep going left, and printing top nodes For right subtree keep going right and printing the right node
its generelly printed in inorder, left -> root -> right
def tree_Coords(root, d, radius, level): if not root: return if level not in d.keys(): d[level] = dict() d[level].update({radius: root.info}) tree_Coords(root.left, d, radius-1, level+1) tree_Coords(root.right, d, radius+1, level+1)
def topView(root): radius = 0 level = 0 if not root: return d = dict() tree_Coords(root, d, radius, level) res = dict()
Giving only 1 unlocked example for this problem is pretty crappy. Would have expected to have to view the bottom left visible element first and worked up to having the root in the middle, not always showing the root element first.