package DataStructures.Trees;// Java program to print top view of Binary treeimport java.util.HashSet;import java.util.LinkedList;import java.util.Queue;// Class for a tree nodeclass TreeNode {// Membersint key;TreeNode left, right;// Constructorpublic TreeNode(int key) {this.key = key;left = right = null;}}// A class to represent a queue item. The queue is used to do Level// order traversal. Every Queue item contains node and horizontal// distance of node from rootclass QItem {TreeNode node;int hd;public QItem(TreeNode n, int h) {node = n;hd = h;}}// Class for a Binary Treeclass Tree {TreeNode root;// Constructorspublic Tree() {root = null;}public Tree(TreeNode n) {root = n;}// This method prints nodes in top view of binary treepublic void printTopView() {// base caseif (root == null) {return;}// Creates an empty hashsetHashSet<Integer> set = new HashSet<>();// Create a queue and add root to itQueue<QItem> Q = new LinkedList<QItem>();Q.add(new QItem(root, 0)); // Horizontal distance of root is 0// Standard BFS or level order traversal loopwhile (!Q.isEmpty()) {// Remove the front item and get its detailsQItem qi = Q.remove();int hd = qi.hd;TreeNode n = qi.node;// If this is the first node at its horizontal distance,// then this node is in top viewif (!set.contains(hd)) {set.add(hd);System.out.print(n.key + " ");}// Enqueue left and right children of current nodeif (n.left != null)Q.add(new QItem(n.left, hd - 1));if (n.right != null)Q.add(new QItem(n.right, hd + 1));}}}// Driver class to test above methodspublic class PrintTopViewofTree {public static void main(String[] args) {/* Create following Binary Tree1/ \2 3\4\5\6*/TreeNode root = new TreeNode(1);root.left = new TreeNode(2);root.right = new TreeNode(3);root.left.right = new TreeNode(4);root.left.right.right = new TreeNode(5);root.left.right.right.right = new TreeNode(6);Tree t = new Tree(root);System.out.println("Following are nodes in top view of Binary Tree");t.printTopView();}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。