Created
September 6, 2017 04:30
-
-
Save courtneyfaulkner/7637a789ccb3c976113b4413892929db to your computer and use it in GitHub Desktop.
[BinaryTreeBottomView] #practice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BinaryTreeBottomView { | |
public static void main(String[] args) { | |
Node root = new Node(20) | |
root.left = new Node(8) | |
root.right = new Node(22) | |
root.left.left = new Node(5) | |
root.left.right = new Node(3) | |
root.right.left = new Node(4) | |
root.right.right = new Node(25) | |
root.left.right.left = new Node(10) | |
root.left.right.right = new Node(14) | |
Tree tree = new Tree(root) | |
println 'Bottom view of the given binary tree:' | |
tree.bottomView() | |
} | |
} | |
class Node { | |
int data | |
int distanceHorizontal | |
Node left, right | |
Node(int key) { | |
data = key | |
} | |
} | |
class Tree { | |
Node root | |
Tree(Node node) { | |
root = node | |
} | |
void bottomView() { | |
if (root == null) | |
return | |
int distanceHorizontal | |
Map<Integer, Integer> map = new TreeMap<>() | |
Queue<Node> queue = new LinkedList<Node>() | |
queue.add(root) | |
while (!queue.isEmpty()) { | |
Node temp = queue.remove() | |
distanceHorizontal = temp.distanceHorizontal | |
map.put(distanceHorizontal, temp.data) | |
if (temp.left != null) { | |
temp.left.distanceHorizontal = distanceHorizontal - 1 | |
queue.add(temp.left) | |
} | |
if (temp.right != null) { | |
temp.right.distanceHorizontal = distanceHorizontal + 1 | |
queue.add(temp.right) | |
} | |
} | |
map.entrySet().each { | |
print it.value + ' ' | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment