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
|
955 Discussions
|
Please Login in order to post a comment
DFs:
public static void top(Node root,Map m,int w,int h){
}
public static void topView(Node root) {
By top view does it mean by top view? From provided example it looks like it traversed only right child only, and the there was no left child in the sample input and output provided. So in case of presence of left child to root will it also traverse left childrens too. In any case I wrote the following java code for traversing left chilrens and right childrens from root and seems to work for base testcase:
Please suggest improvements to this code. Thanks
This question is so terribly defined it makes me wanna p*** in the cereal of whoever made this question. What defines a view of a tree as being top down? Well in the problem description its defined in one single example EXCEPT THE F****** EXAMPLE DOESN'T COVER 80% OF HOW THE VIEW IS DEFINED.
Assuming all branches are evenly spaced: i.e. a left branch is 1 unit down and 1 unit to the left of its parent, the highest branch to be left or right of the root and all of its proceeding children will be what you could see. For example, if the root node has a left child, the left child and all of its left children are what you can see. The highest/first child to be right of the root and all of its right sided children would be visible as well.
If you had: 1 \ 15 / 3 / \ 2 4 Then you could see 15 and all of its proceeding right children, you could also see two since its left of 1 and all of its left children. Since all diagnal lines you could form all have a slope of 1 or -1, you could never have a situation where you could see one of four's imaginarily infine right sided children because 15 set the line of sight at a higher point. Same logic follows that four's imaginarily infine left sided children could never enter the line of sight of root because 2 already determined roots left sided line of sight.
I made one other assumption that branches / connections between branches were opaque. I wrote code based on these priciples. F*** this problem.
`def topView(root, direction="Root"):
""" Node is defined as self.left (the left child of the node) self.right (the right child of the node) self.info (the value of the node) """ 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()