二叉树获取每层的最右一个节点(二叉树的右视图)

	public static void levelPrint(Node head) {
		System.out.println("LevelPrint");
		Node current;
		Queue queue = new LinkedList();
		Stack stack = new Stack();//和stack相关的全是获取最右节点
		queue.add(head);
		stack.add(head);
		System.out.print(stack.peek().value + " ");
		int start = 0;
		int end = 1;
		while(!queue.isEmpty()) {
			current = queue.poll();
			start++;
			stack.add(current);
			if(current.left != null) {
				queue.add(current.left);
				stack.add(current.left);
			}
			if(current.right != null) {
				queue.add(current.right);
				stack.add(current.right);
			}
			if(start == end && !queue.isEmpty()) {
				start = 0;
				end = queue.size();
				System.out.print(stack.peek().value + " ");
			}
		}
	}

你可能感兴趣的:(二叉树)